如何在正则表达式中执行此操作?

时间:2021-01-09 20:45:25

I have a java program, and in one part of my code I have to read a string like this, ^s(group1) ^s(group2) and then return the strings "group1" and "group2" so I used this regexp \^s\(.*\) but it returns the whole string.

我有一个java程序,在我的代码的一部分我必须读取这样的字符串,^ s(group1)^ s(group2)然后返回字符串“group1”和“group2”所以我使用这个正则表达式\ ^ s \(。* \)但它返回整个字符串。

What's wrong?

怎么了?

2 个解决方案

#1


1  

.* matches ) so the match doesn't stop at the close parenthesis. Try [^\)]* instead, or [^\(\)]* if you want a bit of extra insurance against nested parenthetical groups.

。*匹配)所以匹配不会在闭括号处停止。如果你想对嵌套的括号组进行一些额外保险,请尝试[^ \]] *或[^ \(\)] *。

You could also look into using a non-greedy modifier, .*?, which would also solve the problem. Some find that more readable than a negated charset match.

您还可以考虑使用非贪婪的修饰符。* ?,这也可以解决问题。有些人发现它比可否定的charset匹配更具可读性。

#2


0  

You can extract those words with groups.

您可以使用组提取这些单词。

\^s\((.*?)\)

\ 2 -S \((。*?)\)

This says to capture anything in between ^s() and can be used like this.

这表示捕获^ s()之间的任何内容,并且可以像这样使用。

String str = "^s(group1) ^s(group2)";
Matcher m = Pattern.compile("\\^s\\((.*?)\\)").matcher(str);

while (m.find()) {
    System.out.println(m.group(1));
}

Output

产量

group1
group2

#1


1  

.* matches ) so the match doesn't stop at the close parenthesis. Try [^\)]* instead, or [^\(\)]* if you want a bit of extra insurance against nested parenthetical groups.

。*匹配)所以匹配不会在闭括号处停止。如果你想对嵌套的括号组进行一些额外保险,请尝试[^ \]] *或[^ \(\)] *。

You could also look into using a non-greedy modifier, .*?, which would also solve the problem. Some find that more readable than a negated charset match.

您还可以考虑使用非贪婪的修饰符。* ?,这也可以解决问题。有些人发现它比可否定的charset匹配更具可读性。

#2


0  

You can extract those words with groups.

您可以使用组提取这些单词。

\^s\((.*?)\)

\ 2 -S \((。*?)\)

This says to capture anything in between ^s() and can be used like this.

这表示捕获^ s()之间的任何内容,并且可以像这样使用。

String str = "^s(group1) ^s(group2)";
Matcher m = Pattern.compile("\\^s\\((.*?)\\)").matcher(str);

while (m.find()) {
    System.out.println(m.group(1));
}

Output

产量

group1
group2