Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace comma in parentheses using regex in java

Tags:

java

regex

I want to replace comma when its inside parentheses only.

For Example

 Progamming languages (Java, C#, Perl)

TO

Progamming languages (Java or C# or Perl)

but it should not repace comma in following string

Progamming languages Java, C#, Perl

CODE

It will replace correctly but its not matching up.

 String test  = "Progamming languages (Java, C#, Perl)";
 String test1 = "Progamming languages Java, C#, Perl"


 String foo = replaceComma(test);
 String foo1 = replaceComma(test1);


 private static String replaceComma(String test)
 {
    String patternStr= "\\((?:.*)(,)(?:.*)\\)";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher= pattern.matcher(test);

    if(matcher.matches())
    {
      return  test.replaceAll("(,)", " or ");
    }

    return  test;

 }

UPDATE

String.replaceAll("(,)", " or "); will not work when you have string like this

String test = "Learning, languages (Java, C#, Perl)";

so you have to use @polygenelubricants code

like image 506
NETQuestion Avatar asked Sep 12 '10 23:09

NETQuestion


1 Answers

You can use positive lookahead (?=…) like this:

    String COMMA_INSIDE = ",(?=[^()]*\\))";
    String text = "a, b, c, (d, e, f), g, h, (i, j, k)";
    System.out.println(
        text.replaceAll(COMMA_INSIDE, " OR")
    );
    // a, b, c, (d OR e OR f), g, h, (i OR j OR k)

This matches a comma, but only if the first parenthesis to its right is of the closing kind.

The [^…] is a negated character class. [^()] matches anything but parentheses. The * is zero-or-more repetition. The \) (written as "\\)" as a Java string literal) matches a closing parenthesis, literally. The backslash escapes what is otherwise a special metacharacter for grouping.

This assumes that the input string is well-formed, i.e. parentheses are always balanced and not nested.

like image 162
polygenelubricants Avatar answered Oct 12 '22 15:10

polygenelubricants