Home > Net >  Java 8 String regex with shared pattern
Java 8 String regex with shared pattern

Time:05-25

I would like to ask for information on how to set a regular expression: In the exercise I was carrying out, we want to calculate the maximum sequence of 0 surrounded by 1 at the beginning and end of the string. The string is a binary number. I was thinking of solving it by using regular expressions with a "1 [0] 1" pattern. The problem arises when an occurrence of the match contains a final 1 which would be an initial 1 of the following occurrence. For example, if I convert 66561 to binary, it becomes 10000010000000001. Printing the found occurrences in the matcher, I only see the first sequence of 0. Does anyone have any idea how to take all occurrences or what is wrong?

CodePudding user response:

Look at 100000100000000010001. Your pattern "1[0] 1" will swallow the final 1 which might be the begin of a next match.

For binary digits, you could do "10 " using a match with the longest match (most zeroes). However this does not guarantee the last match, should the input ends with a 0.

As already commented you can use a look-ahead match (?=AHEAD):

"10 (?=1)"

There a 1 must follow but is not a part of the match, and the search will continue with that 1.

The comment also used a look-behind match for a preceding 1: (?<=BEHIND)`.

CodePudding user response:

    I used the following code:

  import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Solution {

  public static int solution(int N) {
    int len = 0;
    String result = Integer.toBinaryString(N);
    final String regex = "1[0] 1";
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(result);

    while (matcher.find()) {
      // System.out.println("group: "   matcher.group());
      if (len < matcher.group().length() - 2)
        len = matcher.group().length() - 2;
    }

    return len;
  }

  public static void main(String[] args) {

    int[] intArray = new int[] {
      66561
    };
    for (int i = 0; i < intArray.length; i  ) {
      int res = solution(intArray[i]);
      System.out.println("max gap: "   res);
    }

  }
}
  • Related