在groovy中使用正则表达式进行模式匹配
我有下面的常规代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String myInput="License_All (12313)"
String myRegex="\\(\\d+\\)"
String ResultString
Pattern regex
Matcher regexMatcher
regex = Pattern.compile(myRegex, Pattern.DOTALL);
regexMatcher = regex.matcher(myInput);
List<String> matchList = new ArrayList<String>();
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
for(int i=0;i<matchList.size();i++)
{
myInput=myInput.replaceAll( matchList[i], '')
println matchList[i]
}
println myInput
它应该删除 (12313)
部分,但它给了我下面的输出
(12313)
License_All ()
如何删除所有括号部分 (12313)
?
I have the below groovy code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String myInput="License_All (12313)"
String myRegex="\\(\\d+\\)"
String ResultString
Pattern regex
Matcher regexMatcher
regex = Pattern.compile(myRegex, Pattern.DOTALL);
regexMatcher = regex.matcher(myInput);
List<String> matchList = new ArrayList<String>();
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
for(int i=0;i<matchList.size();i++)
{
myInput=myInput.replaceAll( matchList[i], '')
println matchList[i]
}
println myInput
It is supposed to remove (12313)
part but instead it gives me the below output
(12313)
License_All ()
How do i remove all the bracket portion (12313)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
matchList
将包含匹配的部分,即(12313)
。然后,该值再次被视为replaceAll
中的正则表达式,因此被解释为组。因此,括号不会被移除。相反,您可以直接在
replaceAll
中使用正则表达式:The
matchList
will contain the matched part, i.e.(12313)
. This one is then again taken as regular expression withinreplaceAll
and therefore interpreted as group. Thus the brackets are not removed.Instead you can use your regex directly in
replaceAll
:因为您正在使用
replaceAll
,所以它期望Pattern
作为第一个元素应该这样做...
顺便说一句,您的原始代码可以制作成更惯用的 Groovy (而不是基本上 Java)就像这样——显然,这与你原来的问题有同样的问题,它只是一种更 Groovy 的编写代码的方式:
Becaue you are using
replaceAll
, it is expecting aPattern
as the first elementShould do it...
As an aside, your original code can be made into more idiomatic Groovy (rather than basically Java) like so -- obviously, this has the same issue as in your original question, it's just a more Groovy way of writing code: