0

I want to replace some text in a java string, but I don't want to replace it if the text is inside a section defined by $ and &. Example: The string "$foo& bar foo" with replace text foo would be "$foo& bar $foo&". So the replace text must be escaped using $ and & but not if the escape is already applied. Currently I'm using the regular expression ([^\\$]|^)text([^&]|$) and it works quite well but if only one of the symbols is found the regex doesn't match. Example: for the text "bar $foo" the regular expression ([^\\$]|^)foo([^&]|$) doesn't matches but I want a not match only if both sign are found.

4
  • Will there be multiple words between $ and &? Commented Dec 17, 2016 at 17:50
  • @TheLostMind no, only one Commented Dec 17, 2016 at 17:50
  • add some small, complete and runnable example of what you're doing and we can try to help Commented Dec 17, 2016 at 17:51
  • @greywolf82 - So basically, all foo's should be replaced by $foo& provided the string is not already $foo& right? Commented Dec 17, 2016 at 17:51

1 Answer 1

4

Use negative lookbehind for $ and negative lookahead for &. This will work for you :

public static void main(String[] args) {
    String s = "$foo& bar foo";
    s= s.replaceAll("(?<!\\$)foo(?!&)", "\\$foo&");
    System.out.println(s);
}

O/P :

$foo& bar $foo&
Sign up to request clarification or add additional context in comments.

Comments

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.