1

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

    }

}
2
  • replaceAll(",[\\[\\]]", ",") Commented Dec 5, 2018 at 16:29
  • "hello,[cicuyuv v,]imijmijm".replaceAll(",[\\[\\]]", ",") try this Commented Dec 5, 2018 at 16:30

2 Answers 2

1

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

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

1 Comment

@Spara A hint: when I was an SO beginner, I earned points by posting answers that were just helpful, adding value to the already existing answers posted by more experienced regex users. This an off-topic conversation, I suggest you delete the comment above, and I will remove mine afterwards.
0
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)

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.