tags:

views:

246

answers:

6

Is it possible to have a regex to match a string with alternating 0 and 1? It can end in 0 or 1 and length is arbitrary.

A: 

(010101)|(010100)

High Performance Mark
Except you missed "the length is arbitrary"... ;)
Jason Berkan
Hmmm, when I answered the question it didn't include 'length is arbitrary' ...
High Performance Mark
+11  A: 

A regex for all possible binary strings would be ^(0|1)*$. This includes the empty string. Not including the empty string you would use ^(0|1)+$.

Is that what you're asking?

Edit: If it's the case that you're looking for alternating 0's and 1's, you can do that as well:

^1?(01)*0?$ should match every possible combination. If you want the string to always start with 0 then you can use ^(01)*0?$ (including empty string) or ^(01)+0?$ (excluding empty string).

eldarerathis
I believe he's looking for a string consisting of a pattern of alternating 0s and 1s.
Michael Madsen
@Michael Madsen: Ah, I think you might be right. I wasn't sure exactly what the OP wanted at first, but I've edited that in. Thanks.
eldarerathis
I wouldn't trust the question till he actually edits it to be a little more question-like ... sour grapes? Nahhhh .... just looking for an actually useful question is all.
drachenstern
@drachenstern: I don't think I can construct many other possibilities without being a mindreader anyway, so my answer will just stay at this. Unless the OP comes back and provides some reasonable details, perhaps...
eldarerathis
+7  A: 

Yes, this is possible. (?:01)*0? will allow an arbitrary amount of "01", optionally followed by a 0, assuming PCRE-like regular expressions with non-capturing groups.

Note that this includes the empty string. If you want at least one character (0), or at least one group of "01", that can also be handled with 0(?:10)*1? and (?:01)+0?, respecitvely.

Michael Madsen
What does the `?:` means?
javaguy
@javaguy: Normally in a regex, you can make a capturing group with `()`, and then you can get the part that was matched by that group after the regex engine has looked at your string. However, sometimes you don't actually need or want to capture it. For that purpose, you can use a non-capturing group, which you get by placing the `?:` at the start of the group, like in my answer.
Michael Madsen
If you use (01)* what will be contained in the group?
javaguy
@javaguy: IIRC, when you do a repeating capturing group like that, it only matches the first occurence; to get everything, you need to do the repetition *inside* the group.
Michael Madsen
A: 

Please provide more info. From the information we have the following would work:

[01]+
Plaudit Design - Web Design
He says he wants alternating. There is no alternating there.
Andy Lester
+1  A: 

I assume you want

((01)*(0)?)

But the question is very ambiguous

Novikov
A: 

Simple and straight forward. You want:

[01]+

monokrome