0

I'm trying to replace the second closing tag > in an String Something="<!-- comm --!><tag titi="string1" toto="string2">" using regex in java.

Something.replaceFirst( "^?>","XXXX")

replace the first >

I would like to replace the second closing tag > after string2 to have this result

Something="<!-- comm --!><tag titi="string1" toto="string2"XXXX"

I'm not really familiar with regex. What am I must doing? Thanks

1
  • It's actually quite tricky to do what you're doing. You basically need to count the number of > instances, and then splice the string. Regex can only help you a little bit with this! It looks like you're hacking some html. Maybe use a tool like jsoup which is built to do this? Commented May 28, 2020 at 16:35

1 Answer 1

1

You could match everything, but use capturing groups, so you can paste everything back in around the XXXX.

String something = "<!-- comm --!><tag titi=\"string1\" toto=\"string2\">";
System.out.println(something.replaceFirst("(^.+?>.+?)>(.*$)", "$1XXXX$2"));
  • ( starts the first capturing group
  • ^ anchors to the start of a line
  • .+? matches one or more of any character as few times as it has to
  • > matches '>' literally
  • ) ends the first capturing group
  • > matches '>' literally again, this is the only thing not in a capturing group
  • ( starts capturing group 2
  • .* matches 0 or more of any character
  • $ anchors to the end of the line

  • $1 refers to the first capturing group (everything before the second '>')

  • $2 refers to the second capturing group (everything that might come after the second '>')
Sign up to request clarification or add additional context in comments.

7 Comments

You can do this with a single \K right?: .+?>.+?\K>
Possibly, although I remember now java doesn't like \K very much - if I were you I'd scrap the solution I just gave you and I'll edit my answer with a more java-friendly one.
Updated my answer to use capturing groups, I think you'll find they work better in java.
That's odd... it works for me. Have you tried stripping it down to a simple test case? I edited my code to include a println, try just copying that verbatim into your main method and see what happens.
It doesn't work for me because I have another tag in the com Something="<!-- <comm> --!><tag titi="string1" toto="string2">" I think that I must Add .+?> in the $1 to have this something.replaceFirst("(^.+?>.+?>.+?)>(.*$)", "$1XXXX$2")
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.