Danny Petrunov
Danny Petrunov

Reputation: 101

Find index of first element of last group regex?

I have the following problem: I have a collection of strings who look kinda like this:

"01100110011"
"11100110010"
"10001110000"

Could there be written a regex that finds the index of the first one in the last group of ones? I am currently using hashmaps and lots of calculations related to lastindexof indexof etc. But at this point it's starting to look ridiculous.

Upvotes: 1

Views: 161

Answers (1)

nhahtdh
nhahtdh

Reputation: 56829

It is quite simple, compile the following regex and search for the first match with Matcher.find():

".*(?<!1)(1)"

You can get the index by calling .start(1) on the Matcher object.

The regex basically finds the last 1, which is not immediately preceded by another 1 (?<!1), which effectively finds the first one in the last group of consecutive 1's.

Sample code:

int startingIndexOfLastGroup(String str) {
    Pattern p = Pattern.compile(".*(?<!1)(1)");
    Matcher m = p.matcher(str);

    if (m.find()) {
        return m.start(1);
    }

    // Return -1 for a string without 1
    return -1;
}

The regex above is simple, but not very nice, since it backtracks quite a bit. If you don't want too much backtracking, you can use the following regex:

"(?:[^1]*+(1+))*+"

Simply put, it will search for 0 or more of non-1 characters [^1]*+, followed by one or more of 1's (1+), and such sequence repeated as many times as possible. Since a repeated capturing group only stores the index of the last capture, it will effective record the start index of the last group of consecutive 1's.

Upvotes: 2

Related Questions