我的数据如下:
0.1.2
[2.2.0, 2.2.1, 2.2.2, 2.2.3]
我想写一个测试,可以识别第一行中的最后一个数字,即2
,然后使用它来匹配第二行中每个值的第二个数字。
所以从第一行开始它会抓住2
,然后在第二行它会抓住2
。
我一直试图用this site为这个任务写一些正则表达式,我试过像[^\d\.\d\.]\d
......但无济于事。
有谁知道如何使用正则表达式从字符串2
中提取0.1.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));
}
}