我的数据是这样的:
0.1.2
[2.2.0, 2.2.1, 2.2.2, 2.2.3]
我想编写一个测试来识别第一行中的最后一位数字,即 2
,然后使用它来匹配第二行中每个值的第二位数字。
所以从第一行开始它会获取 2
,然后在第二行它会获取 2
。
我一直在尝试使用 this site 为这个任务编写一些正则表达式,我尝试了类似 [^\d\.\d\.]\d
... 但无济于事。
有谁知道我如何使用正则表达式从字符串 0.1.2
中提取 2
,从 2.2 等字符串中提取中间数字.0
和 2.2.1
?
最佳答案
您可以使用两个正则表达式,一个从第一行获取 2
,另一个从第二行获取所有三元组。
String s = "0.1.2\n" +
"[2.2.0, 2.2.1, 2.2.2, 2.2.3]";
Matcher m = Pattern.compile("\\d\\.\\d\\.(\\d)\n(.+)").matcher(s);
if (m.find()) {
int lastDigit = Integer.parseInt(m.group(1)); // find the last digit on first line
String secondLine = m.group(2);
// now find triplets on the second line
m = Pattern.compile("(\\d)\\.(\\d)\\.(\\d)").matcher(secondLine);
while (m.find()) {
// here I printed the digits out. You can do whatever you like with "m.group(lastDigit)"
System.out.println(m.group(lastDigit));
}
}
关于Java正则表达式跳过一些字符只匹配一次出现的数字,间歇句点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53487128/