2

Here I am doing automation with Java, serenity with rest-assured. So I want to replace the 2nd <p> & </p> tags with a blank string.

Here I attached the template

<Request>    
    <P>
        <n>name1</n>
        <v>${value1}</v>
    </P>
    <P>
        <n>name2</n>
        <v>${value2}</v>
    </P> 
   <P>
        <n>name3</n>
        <v>value3</v>
    </P> 
</Request>

I am using the below code to replace the 2nd <p> and </p> tags. But it was replaced the all <p> &</p> tags(first and last <p> & </p> tags also)

String request = exampleTemplate.replace("${value1}", "XYZ")
                .replace("<P>", "")
                .replace("<v>${value2}</v>", "1234")
                .replace("</P>", "")
                .replace("${value3}", "AAA");

How can I replace only the 2nd <p> and </p> tags?

kithmi
  • 85
  • 2
  • 9

1 Answers1

2

You can match both the first and second <p> elements together.

String res = str.replace("${value1}", "XYZ")
                .replace("<v>${value2}</v>", "1234")
                .replace("${value3}", "AAA")
                .replaceFirst("(?s)(<P>.*?</P>\\s*)<P>(.*?)</P>", "$1$2");

Demo

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thanks for the regular expression. Is there any way to replace last '

    ' & '

    ' tags.?
    – kithmi Mar 24 '21 at 04:43
  • 2
    This is a very intelligent way of using regex for this solution. @kithmi - you can learn more about regex from [Learning Regular Expressions](https://stackoverflow.com/q/4736/10819573). However, I suggest you try solving these kinds of problems using an XML parser. – Arvind Kumar Avinash Mar 24 '21 at 11:31