我想使用正则表达式来分割这个字符串:
String filter = "(go|add)addition|(sub)subtraction|(mul|into)multiplication|adding(add|go)values|(add|go)(go)(into)multiplication|";
我希望将其拆分为|
,除非管道出现在括号内,在这种情况下它们应该被忽略,即我输出的结果如下:
(go|add)addition
(sub)subtraction
(mul|into)multiplication
adding(add|go)values
(add|go)(go)(into)multiplication
更新
然后我想在开头到结尾的括号内移动单词。
像这样......
addition(go|add)
subtraction(sub)
multiplication(mul|into)
adding(add|go)values
multiplication(add|go)(go)(into)
我试过这个正则表达式:Splitting of string for `whitespace` & `and`但是他们使用了引号而我无法使其适用于括号。
答案 0 :(得分:3)
15分钟前已经看过这个问题。现在它被正确地问了,这是我的回答命题:
尝试使用正则表达式很复杂,因为您需要计算括号。我建议你手动解析字符串,如下所示:
public static void main(String[] args) {
String filter = "(go|add)addition|(sub)subtraction|(mul|into)multiplication|";
List<String> strings = new LinkedList<>();
int countParenthesis = 0;
StringBuilder current = new StringBuilder();
for(char c : filter.toCharArray()) {
if(c == '(') {countParenthesis ++;}
if(c == ')') {countParenthesis --;}
if(c == '|' && countParenthesis == 0) {
strings.add(current.toString());
current = new StringBuilder();
} else {
current.append(c);
}
}
strings.add(current.toString());
for (String string : strings) {
System.out.println(string+" ");
}
}
输出:
(go|add)addition
(sub)subtraction
(mul|into)multiplication
答案 1 :(得分:2)
如果你没有有嵌套的括号(所以不 (mul(iple|y)|foo)
)你可以使用:
((?:\([^)]*\))*)([^()|]+(?:\([^)]*\)[^()|]*)*)
( #start first capturing group
(?: # non capturing group
\([^)]*\) # opening bracket, then anything except closing bracket, closing bracket
)* # possibly multiple bracket groups at the beginning
)
( # start second capturing group
[^()|]+ # go to the next bracket group, or the closing |
(?:
\([^)]*\)[^()|]* # bracket group, then go to the next bracket group/closing |
)* # possibly multiple brackets groups
) # close second capturing group
并替换为
\2\1
<强>解释强>
((?:\([^)]*\))*)
匹配并捕获开头的所有括号组[^()|]*
除(
,)
或|
之外的任何内容。如果没有任何括号,这将匹配所有内容。(?:\([^)]*\)[^()|]*)
:(?:...)
是非捕获组,\([^)]*\)
匹配括号内的所有内容,[^()|]*
将我们转到下一个括号组或|
结束比赛。代码示例:
String testString = "(go|add)addition|(sub)subtraction|(mul|into)multiplication|adding(add|go)values|(add|go)(go)(into)multiplication|";
Pattern p = Pattern.compile("((?:\\([^)]*\\))*)([^()|]+(?:\\([^)]*\\)[^()|]*)*)");
Matcher m = p.matcher(testString);
while (m.find()) {
System.out.println(m.group(2)+m.group(1));
}
输出(demo):
addition(go|add)
subtraction(sub)
multiplication(mul|into)
adding(add|go)values
multiplication(add|go)(go)(into)
答案 2 :(得分:0)
你的字符串
&#34;(去|添加)另外|(分)减法|(MUL |成)乘法|&#34;
有一个模式|(你可以从这里分割出这个特殊的String模式。但如果你的子字符串包含paranthesis(&#34;(&#34;)在ex:
之间,那么这不会给出预期的结果(go |(add))另外....继续
希望这会有所帮助。
答案 3 :(得分:0)
如果您在括号内,请设置bool以保持跟踪。
Bool isInside = True;
loop through string
if char at i = ")" isInside = False
if isInside = false
code for skipping |
else
code for leaving | here
这样的事情我觉得应该有用。