1

I'm having a problem. I'm trying to figure out what is the regular expression for the following situation, where I want to match one of the follwoing if returned back.

               ABC 1 or 
               ABC 1 0  or
               ABC 1 0 1  or 
               ABC 1 0 1 0 or etc

I'm trying the following to acheive this but its only matching the first string (ABC 1).

               regular expression: ABC (1|0)+

I have been trying to figure this out for a long time and I can't seem to figure it out. Could someone please help?

Thanks

3
  • You may want to include a combination of spaces and 1s and 0s probably? Commented Sep 19, 2013 at 19:23
  • ABC( (1|0))+ perhaps? Or ABC( 1 0)*( 1)? if you must have alternating 0's and 1's. Commented Sep 19, 2013 at 19:28
  • I'd probably try ABC(\s(1|0))+ Commented Sep 19, 2013 at 19:30

2 Answers 2

2

If you want to make sure it's first a 1, then a 0, then another 1, then a 0 etc, you might use this:

re.match(r'ABC(?: 1(?: 0|$))+$', s)

regex101 demo

EDIT: If you don't care about the order, you can use this:

re.match(r'ABC(?: [01])+$', s)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but I dont want to change from 0 to 1. I just have a response where I have a string and numbers.
@user2796819 There was someone else who had posted an answer with a regex to match any order, but he deleted his answer and I don't know why :( Anyway, see if the second regex works for you!
0

ABC1(01)*0?

ABC, then 1, then zero or more 0 1, and finally an optional 0. Assuming you don't want white spaces, of course.

If you want a single space after each "part":

ABC 1( 0 1)*( 0)?

1 Comment

To the downvoters: I believe you are mistaken. The way I understand the question, he wants "ABC" and then a sequence of 1's and 0's, alternating, ending in either a 1 or a 0. I was neglecting whitespace, of course.

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.