Java regex skip some characters match only one occurrence of digit, with intermittent periods

smatthewenglish :

My data looks like this:

0.1.2
[2.2.0, 2.2.1, 2.2.2, 2.2.3]

I'd like to write a test that can identify the last digit in the first line, i.e. 2, and subsequently use that to match the second digit of each value in the second line.

So from the first line it would grab 2, and then in the second line it would grab 2.

I've been trying to write some regex for this task using this site, I tried something like [^\d\.\d\.]\d... but to no avail.

Does anyone know how I could use regex to extract the 2 from the String 0.1.2, to to extract the middle digit from such strings as 2.2.0, and 2.2.1?

Sweeper :

You can use two regexes, one to get the 2 from the first line, the other to get all the triplets from the second line.

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));
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77983&siteId=1