[英]How to match the ending parenthesis using regex in java?
I have some pattern which i want to match using java regex.The pattern sometimes has brackets sometimes it does not have.我有一些我想使用 java 正则表达式匹配的模式。模式有时有括号,有时它没有。 Example of pattern:
模式示例:
Test string: (2555.45)
Test string: 50.00
Test string: 2345,46.00
I have wrote the below program but somehow it does not take the ending parentheses when I tried to match.我已经编写了下面的程序,但是当我尝试匹配时,它以某种方式没有使用结尾括号。
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main( String args[] ) {
String re = ".*Test string:\\s+([^\\\\d]+\\d[.,]\\d+).*";
Pattern p = Pattern.compile(re);
List<String> inputs = Arrays.asList( "Test string: (2555.45)", "Test string: 50.00", "Test string: 2345,46.00", "Test string: 620.26","Test string: 37687.20" );
//for (String s : arr) {
// System.out.println(s.matches(re));
//}
inputs.forEach(in->{
Matcher m = p.matcher(in);
if (m.matches()) {
System.out.println(m.group(1));
}
});
}
}
What I might be missing here.Any clue will be helpful我可能在这里遗漏了什么。任何线索都会有所帮助
The parenthesis ( (
and )
), are special characters to the regular expression engine.括号(
(
和)
)是正则表达式引擎的特殊字符。 To go around this, we escape them by adding an extra \
in front.在 go 周围,我们通过在前面添加一个额外的
\
来逃避它们。 Due to how Java works, we need to escape that extra \
again, so to match (
and )
in Java you would need to have \\(
or \\)
.由于 Java 的工作方式,我们需要再次转义额外的
\
,因此要匹配 Java 中的(
和)
,您需要有\\(
或\\)
。
Since in your test case the parenthesis might or might not be there, I suggest you add a ?
由于在您的测试用例中括号可能存在也可能不存在,我建议您添加一个
?
operator.操作员。 I also noticed (unless I am missing something) that you are expecting to match 2
:
characters as opposed to one.我还注意到(除非我遗漏了什么)你期望匹配 2
:
字符而不是一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.