Capture part of a string within a pair of <> characters using regex

Asked

Viewed 526 times

0

I’m trying to solve a problem that consists of exchanging words that are between <>.

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

In addition to this string, I receive a parameter indicating which or which words in the string I should exchange for a value x and the case-sensitive between words should be ignored.

In the case of the example, PALAVRA and palavra are equal to each other and to the parameter, outrapalavra differs from the two and the parameter and should not be changed. I should only exchange < PALAVRA > and </ PALAVRA > which are just between the characters <> and </>.

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

If it were only to compare the parameter with the words, it would have already solved, but with the restriction of having to ignore the case-sensitive I couldn’t find a solution I wouldn’t use regex to find the target word independent of the characters that compose it capital letters or minuscule.

Does anyone have any tips?

1 answer

0


Try it like 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);

The replace works like this :

  • < literal capture
  • / if you have
  • .*? anything, as little as possible
  • parametro word to be replaced
  • .*? anything, as little as possible
  • > literal capture

Check it out at Ideone.

  • That’s exactly what I was trying to do, but I was missing some details that I didn’t know at the time. I had no idea. Thanks for the help. How do I close the topic?

  • @Lucasoliveira the question is closed, when it has an accepted answer, but does not want to say that you can receive new notifications, it just stops appearing in the feed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.