0

I want to write a regex such that it matches all binary strings of length zero or more. The requirement is that the odd position must be 1 and even position can be either 1 or 0.

I am not sure how to control positions with regex?

My idea is something like ([1]+[01]*)+

Sample:

  • 10101

  • 11111

3
  • Can 1 come in an even position too? Commented Aug 4, 2013 at 7:25
  • Can you please add some sample binary strings for better understanding? Commented Aug 4, 2013 at 7:25
  • Yes it can come in even position. Commented Aug 4, 2013 at 7:26

2 Answers 2

2

You should remove that quantifier from inside. Also, since you want to match 0 length string, you need to use * quantifier on complete regex, instead of +.

Try using the following regex:

(1[01]?)*

This will match:

  • 1 at first place
  • Then 0 or 1 in the 2nd place.
  • 0 or more repetition, will make every odd position filled with 1, and even position can contain 0 or 1.
  • [01] is optional to match odd length string.
Sign up to request clarification or add additional context in comments.

2 Comments

Just to confirm if it is round bracket (), then * or + means repetition but if it is square bracket [], then * or + means combination?
@Mat.S. This is to do with the character class. A character class can matches a single character out of all the character inside []. So, + or *, is repetition only. Just that, it will match repetition of any character from [].
1

try using this :

String data = "10111";
        Pattern pattern = Pattern.compile("(1[01]?)*");

        Matcher matcher = pattern.matcher(data);
        while (matcher.find()) {
            // Indicates match is found. Do further processing
            System.out.println(matcher.group());
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.