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

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
Pkdrc
  • 43
  • 1
  • 7
  • 2
    In java, `String`s 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()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-) if you don't actually want to work with regex (this way you wont have to deal with things such as escaping the pipes). – maloomeister Jun 24 '21 at 07:18
  • Every `|` must escaped with backslash. So try `\|\|`. – Reporter Jun 24 '21 at 07:18
  • You should use replace (which doesn't take a regex) rather than replaceAdd (which does). – NomadMaker Jun 24 '21 at 07:40
  • @JonnyHenly The pipe is in regex the or operator. According regex101.com confirms my words. – Reporter Jun 24 '21 at 07:46

3 Answers3

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

string.Empty
  • 10,393
  • 4
  • 39
  • 67
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
Kapitany
  • 1,319
  • 1
  • 6
  • 10
  • 2
    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`? – maloomeister Jun 24 '21 at 07:33
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("|| '-' || ", ",").

Kristof Neirynck
  • 3,934
  • 1
  • 33
  • 47