Reputation: 7346
I have few string datasets in which I would like to replace a certain combination of characters using the regex replace in java. I tried multiple patterns but none of them helped. Could someone point me in the right pattern?
For example:
hello,[cicuyuv v,]imijmijm
in this string i want to replace ",["
and ",]"
with a single ","
wherever occured.
public class MainApp {
public static void main(String[] args) {
String data = "hello,[cicuyuv v,]imijmijm"
.replaceAll("[,[\\[]]", ",");
System.out.println(data);
}
}
Upvotes: 1
Views: 769
Reputation: 7679
System.out.println("hello,[cicuyuv v,]imijmijm".replaceAll(",(\\]|\\[)" , ","));
, matches the character , literally (case sensitive)
Capturing Group (\\]|\\[)
1st Alternative \]
\] matches the character ] literally (case sensitive)
2nd Alternative \[
\[ matches the character [ literally (case sensitive)
Upvotes: 0
Reputation: 626748
Your "[,[\\[]]"
represents a [,[\[]]
pattern that matches a single char, either a ,
or a [
(the [\[]
character class inside another character class formed a character class union).
You may use
String data = "hello,[cicuyuv v,]imijmijm".replaceAll(",[\\[\\]]", ",");
System.out.println(data); // -> hello,cicuyuv v,imijmijm
See the Java demo
Here, ,[\[\]]
is a regex pattern that matches ,
and then a [
or ]
. Please be very careful with ]
and [
inside a character class in a Java regex: they must both be escaped (in other flavors, and when you test at regex101.com or other similar sites, [
inside [...]
does not have to be escaped. It is advised to use Java regex testing sites, like RegexPlanet or Java Regular Expression Tester (no affiliation).
Upvotes: 1