Capture part of a string within a couple of characters using regex

0

I'm trying to solve a problem of exchanging words between <> .

For example, I have the following string: <><PALAVRA outrapalavra>palavra</PALAVRA>

In addition to this string, I get a parameter that indicates which words in the string should be exchanged for a x value, and the case-sensitive between words should be ignored.

In the example example, PALAVRA and palavra are equal to each other and to the parameter, outrapalavra differs from the two and parameter e and should not be changed. I need to change only < PALAVRA > and </ PALAVRA > that are just between the characters <> and </> .

I tried with the following expression <(?parâmetro.*?)> but I was not successful because when executing the <> is removed and everything that is between <> is captured.

If I were just comparing the parameter with the words I would have solved it, but with the restriction of having to ignore case-sensitive I found no other solution than using regex > to find the target word independent of the characters that make it up uppercase or lowercase .

Does anyone have any tips?

    
asked by anonymous 29.01.2016 / 19:00

1 answer

0

Try this:

String s = "<><PALAVRA outrapalavra>palavra</PALAVRA>";
String parametro = "palavra";
String replace = "NovaPalavra";

Pattern p = Pattern.compile("<(/?)(.*?)"+parametro+"(.*?)>", Pattern.CASE_INSENSITIVE);
s = p.matcher(s).replaceAll("<$1$2"+replace+"$3>");

System.out.print(s);

replace works like this:

  • % literal capture%
  • < if it has
  • / anything, as little as possible
  • .*? word to be replaced
  • parametro anything, as little as possible
  • % literal capture%

See Ideone.

    
01.02.2016 / 12:37