简体   繁体   中英

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 :)

你可以做类似的事情

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

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.

请参阅Java regex教程,并检出字符类和捕获组。

The PCRE would be:

/invalid_content/

For a simple substitution. What more do you want?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM