RE: Fun Regex Exercise
by dchetlin (Friar) on Oct 25, 2000 at 16:31 UTC
|
/me tries to figure out how to do a spoiler in web-space...
Spoiler follows!...
/^(1[01]*1|0[01]*0)$/
or, if I can use backreferences (wasn't clear if grouping meant _only_ grouping):
/^([01])[01]*\1$/
-dlc | [reply] |
|
| [reply] [d/l] |
|
| [reply] [d/l] |
|
| [reply] [d/l] |
|
| [reply] |
|
Just so folks know should they stumble on this node there is now support for <spoiler> tags in PM. They can be configured to render just like this too. :-) IOW, please DONT follow the advice here from tilly, just use the correct tags.
---
$world=~s/war/peace/g
| [reply] |
|
Bravo (or brava, depending...). My solution was different,
but could (and should) have been optimized into yours. Mine
uses the notion that any matching string looks like a series
of strings like "11..1100..00" concatenated, with a string of
1's at the end. (Or vice-versa, with 0's...) But yours is
far simpler -- in fact, it states the very fact: if there's
a 1 (or 0) at both ends, the string will succeed. Oh, and
no backreferences, but that's ok.
Here's mine. It seems like even more of a behemoth now...
/^((1+0+)*1+|(0+1+)*0+)$/
"Ewww," Tom said sheepishly.
$_="goto+F.print+chop;\n=yhpaj";F1:eval | [reply] [d/l] |
RE: Fun Regex Exercise
by quidity (Pilgrim) on Oct 25, 2000 at 18:04 UTC
|
Nice Challenge
Basically you need to check for any string which begins and ends with the same character, any sequence of 0s or 1s inside this will match the '10|01' criteria. You also need to account for '1', '0', '11' and '00' as these also meet the '01|10' constraint.
/
^(0|1)$ # simple cases of 1 or 0, with zero 01|10
|
^1(0|1)*1$ # 1 .. anything .. 1
|
^0(0|1)*0$ # 0 .. anything .. 0
/x
my @tests = qw(
0 1
01 10 00 11
000 111 001 011 101 010 100 110
1001 1101 0101 1010
);
foreach (@tests) {
print "$_ ";
if (/^(0|1)$|^1(0|1)*1$|^0(0|1)*0$/) {
print "passed\n";
}
else {
print "failed\n";
}
}
| [reply] [d/l] [select] |
|
/^[01]$|^([01])[01]*?\1$/
ciao | [reply] [d/l] |
|
| [reply] |
RE: Fun Regex Exercise
by merlyn (Sage) on Oct 25, 2000 at 17:37 UTC
|
spoiler
Well, in english, it'd have to be a string that if non-empty, began
with a 0 or 1, and then either stops there or has zero or 0's or 1's followed by
what the string started with. That seems to fit the description.
So as a regex would be:
/^(([01])([01]*\2)?\z/
-- Randal L. Schwartz, Perl hacker | [reply] [d/l] |