我必须使用正则表达式组从字符串中提取值。
输入是这样的,
-> 1
-> 5.2
-> 1(2)
-> 3(*)
-> 2(3).2
-> 1(*).5
现在我编写以下代码以从这些输入中获取值。
String stringToSearch = "2(3).2";
Pattern p = Pattern.compile("(\\d+)(\\.|\\()(\\d+|\\*)\\)(\\.)(\\d+)");
Matcher m = p.matcher(stringToSearch);
System.out.println("1: "+m.group(1)); // O/P: 2
System.out.println("3: "+m.group(3)); // O/P: 3
System.out.println("3: "+m.group(5)); // O/P: 2
但是,我的问题是只有第一组是必修的,其他组是可选的。
这就是为什么我需要像这样的正则表达式,它将检查所有模式并提取值。
最佳答案
使用非捕获组并通过在这些组旁边添加 ?
量词将它们变为可选。
^(\d+)(?:\((\d+|\*)\))?(?:\.(\d+))?$
Java 正则表达式是,
"(?m)^(\\d+)(?:\\((\d\+|\\*)\\))?(?:\\.(\\d+))?$"
例子:
String input = "1\n" +
"5.2\n" +
"1(2)\n" +
"3(*)\n" +
"2(3).2\n" +
"1(*).5";
Matcher m = Pattern.compile("(?m)^(\\d+)(?:\\((\\d+|\\*)\\))?(?:\\.(\\d+))?$").matcher(input);
while(m.find())
{
if (m.group(1) != null)
System.out.println(m.group(1));
if (m.group(2) != null)
System.out.println(m.group(2));
if (m.group(3) != null)
System.out.println(m.group(3));
}
关于java - 使用正则表达式组从字符串中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28109089/