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
You can use positive lookahead
(?=…)like this: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.