JuanDeLosMuertos
JuanDeLosMuertos

Reputation: 4620

replacing regex in java string

I have this java string:

String bla = "<my:string>invalid_content</my:string>";

How can I replace the "invalid_content" piece?

I know I should use something like this:

bla.replaceAll(regex,"new_content");

in order to have:

"<my:string>new_content</my:string>";

but I can't discover how to create the correct regex

help please :)

Upvotes: 1

Views: 2453

Answers (5)

stili
stili

Reputation: 674

See Java regex tutorial and check out character classes and capturing groups.

Upvotes: 1

Peter Boughton
Peter Boughton

Reputation: 112160

Mark's answer will work, but can be improved with two simple changes:

  • The central parentheses are redundant if you're not using that group.
  • Making it non-greedy will help if you have multiple my:string tags to match.

Giving:

String ResultString = SubjectString.replaceAll
    ( "(<my:string>).*?(</my:string>)" , "$1whatever$2" );


But that's still not how I'd write it - the replacement can be simplified using lookbehind and lookahead, and you can avoid repeating the tag name, like this:

String ResultString = SubjectString.replaceAll
    ( "(?<=<(my:string)>).*?(?=</\1>)" , "whatever" );

Of course, this latter one may not be as friendly to those who don't yet know regex - it is however more maintainable/flexible, so worth using if you might need to match more than just my:string tags.

Upvotes: 6

Gumbo
Gumbo

Reputation: 655239

Is invalid_content a fix value? If so you could simply replace that with your new content using:

bla = bla.replaceAll("invalid_content","new_content");

Upvotes: 0

strager
strager

Reputation: 90012

The PCRE would be:

/invalid_content/

For a simple substitution. What more do you want?

Upvotes: 0

Mark Davidson
Mark Davidson

Reputation: 5513

You could do something like

String ResultString = subjectString.replaceAll("(<my:string>)(.*)(</my:string>)", "$1whatever$3");

Upvotes: 8

Related Questions