user1739581
user1739581

Reputation: 85

Regex: find a variable number sequence

I am looking for a specific sequence of numbers in a line. I can best explain with an example:

00001 # first search criteria - line 1
00010 # second search criteria - line 2

So every line has 5 digits of either 0 or 1. I am looking for the combination of all 0 except for 1 digit that can be a 1. This 1 can be in any position of the 5 digits.

The regex code I have for 5 digits of 0 is

^((0\s*?){5}) # there may be spaces between the numbers

The line 1 case above would be selected with following regex code:

^((0\s*?){4})\s*(1)

My question is how I could write in regex code the changing position of 1 to cover the 5 cases/positions. Thank you.

Upvotes: 2

Views: 118

Answers (2)

user557597
user557597

Reputation:

You can use two conditionals.
First one insures 1 is not found again.
Second one insures 1 is found.

(?:((?(1)(?!))1)|0){5}(?(1)|(?!))

Expanded

 (?:
      (                             # (1 start)
           (?(1) (?!) ) 1
      )                             # (1 end)
   |  0
 ){5}
 (?(1) | (?!) )

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You can use a lookahead based regex for this:

^(?=[0\s]*1[0\s]*$)(?:\s*[01]\s*){5}$

RegEx Demo

Lookahead (?=[0\s]*1[0\s]*$) will enforce only single 1 at any position in input where as (?:\s*[01]\s*){5} will make sure that input has only 0 and 1 with 5 digits length also allowing white-spaces anywhere.

Upvotes: 1

Related Questions