Java正则表达式跳过一些字符只匹配一次出现的数字,具有间歇性句点

问题描述 投票:4回答:1

我的数据如下:

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.02.2.1等字符串中提取中间数字?

java regex
1个回答
4
投票

您可以使用两个正则表达式,一个用于从第一行获取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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.