在java中使用regex替换括号中的逗号
我想仅在内部括号中替换逗号。
I want to replace comma when its inside parentheses only.
例如
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
代码
它会正确替换但不匹配。
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;
}
更新
String.replaceAll((,),或);
在你有这样的字符串时不起作用
String.replaceAll("(,)", " or ");
will not work when you have string like this
String test =学习,语言(Java,C#,Perl);
String test = "Learning, languages (Java, C#, Perl)";
所以你必须使用@ polygenelubricants code
so you have to use @polygenelubricants code
你可以使用正 lookahead (?= ...)
喜欢这样:
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.
[^ ...]
是否定角色类。 [^()]
匹配除括号外的任何内容。 *
为零或更多重复。 \)
(写为\\)
作为Java字符串文字)匹配右括号从字面上看。反斜杠逃脱了分组的特殊元字符。
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.