1

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

Jose Luis
3,3813 gold badges38 silver badges54 bronze badges
asked Jan 31, 2009 at 20:33

5 Answers 5

8

You could do something like

String ResultString = subjectString.replaceAll("(<my:string>)(.*)(</my:string>)", "1ドルwhatever3ドル");
answered Jan 31, 2009 at 20:42
Sign up to request clarification or add additional context in comments.

Comments

6

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>)" , "1ドルwhatever2ドル" );


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.

answered Feb 1, 2009 at 15:05

Comments

1

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

answered Feb 1, 2009 at 17:19

Comments

0

The PCRE would be:

/invalid_content/

For a simple substitution. What more do you want?

answered Jan 31, 2009 at 20:42

1 Comment

A solution that works in Java, maybe? Besides, I think the surrounding XML tags are needed to identify the invalid content, and that's what the OP was having trouble with.
0

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");
answered Jan 31, 2009 at 20:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.