1

I have a string and I need to replace || '-' || with , using regex. Please find the code below:

String str= "str1 || '-' || str2";
str.replaceAll("|| '-' || ", ","); 

This replaceAll method is not working. Can anyone please suggest the correct way.

Output should be: str1,str2

4
  • 2
    In java, Strings are immutable. You are not actually reassigning your str variable with the result of the replaceAll. Also, replaceAll takes a regular expression as an input. Use replace() if you don't actually want to work with regex (this way you wont have to deal with things such as escaping the pipes). Commented Jun 24, 2021 at 7:18
  • Every | must escaped with backslash. So try \|\|. Commented Jun 24, 2021 at 7:18
  • You should use replace (which doesn't take a regex) rather than replaceAdd (which does). Commented Jun 24, 2021 at 7:40
  • @JonnyHenly The pipe is in regex the or operator. According regex101.com confirms my words. Commented Jun 24, 2021 at 7:46

3 Answers 3

3

Don't use replaceAll(), rather use replace() because replaceAll uses regex and you do not need regex in this situation.

str = str.replace("|| '-' || ", ",");

If you are here because you have to use regex, the pipe character (|) is a special regex character and in this situation you would need to escape special characters by using a \ character infront.

As shown here: Escaping special characters in Java Regular Expressions

Sign up to request clarification or add additional context in comments.

1 Comment

The best solution, not using regex. But you could mention that | is a special regex symbol.
2

Try the following statement:

String strMod = str.replaceAll("\\s\\|\\| '-' \\|\\| ", ",");

The strMod variable will contain the modified value.

The key points are:

  • use escape char in the regular expression because the pipe character has a special meaning in the regexp
  • use the result value of the replaceAll method

1 Comment

Not sure why this is the accepted answer. There is no actual use case for using regex here. Only some simple text replacement. So why go the way of escaping the whole thing, instead of simply suggesting to use replace instead of replaceAll?
1

The | character has special meaning in regex. You can escape it by prefixing it with a \. You can also use Pattern.quote() to escape the whole string.

But in this case it might be better not to use a regex. You want to replace literal text. Try str.replace("|| '-' || ", ",").

1 Comment

According regex101.com , only the pipe must be escaped.

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.