我的数据如下:
0.1.2
[2.2.0, 2.2.1, 2.2.2, 2.2.3]
我想写一个测试,可以识别第一行中的最后一个数字,即2
,然后使用它来匹配第二行中每个值的第二个数字。
因此,从第一行开始,它将获取2
,然后在第二行中获取2
。
我一直在尝试使用这个网站为这个任务编写一些正则表达式,我尝试了[^d.d.]d
之类的东西。。。但无济于事。
有人知道我如何使用regex从字符串0.1.2
中提取2
,从2.2.0
和2.2.1
等字符串中提取中间数字吗?
您可以使用两个正则表达式,一个从第一行获取2
,另一个从第二行获取所有三元组。
String s = "0.1.2n" +
"[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));
}
}