I'm falling-over with another regex problem that would appear to be fairly straightforward; I just can't seem to get my head to work with regex very well :(
I simply want to match a string like "comp.hw." against other strings that might be like "comp.hw.new" or "comp.sw.old", etc. The thinking might be to say that I want to match on the "2nd occurrence of a '.'"... and to retain the string up to that point... and then proceed to match the resultant string against whatever.
perlre... and "Perl Cookbook" don't really help me too much...
So, I've resorted to rubbish like the following code:
#!/usr/bin/perl #! $master = "comp.hw."; @items = ( "comp.", "comp.hw.", "comp.hw.new.", "comp.hw.hw.", "comp.sw.old.", "muse.hw.new.", "ancient." ); for ($level = 1; $level < 4; $level++) { printf("Match Level: $level\n"); # $level = no. of '.' to match @m = split(/\./, $master); $num_m = @m; $buf = ""; for ($i = 0; $i < $level; $i++) { if ($i >= $num_m) { last; } $buf .= $m[$i] . "."; } printf("Master: >%s<\n", $buf); foreach $str (@items) { if ($str =~ /^$buf/i) { printf("\t%s MATCHES %s\n", $str, $buf); } else { printf("\t%s DOES NOT MATCH %s\n", $str, $buf); } } printf("\n"); }
...which produces the following output:-
Match Level: 1 Master: >comp.< comp. MATCHES comp. comp.hw. MATCHES comp. comp.hw.new. MATCHES comp. comp.hw.hw. MATCHES comp. comp.sw.old. MATCHES comp. muse.hw.new. DOES NOT MATCH comp. ancient. DOES NOT MATCH comp. Match Level: 2 Master: >comp.hw.< comp. DOES NOT MATCH comp.hw. comp.hw. MATCHES comp.hw. comp.hw.new. MATCHES comp.hw. comp.hw.hw. MATCHES comp.hw. comp.sw.old. DOES NOT MATCH comp.hw. muse.hw.new. DOES NOT MATCH comp.hw. ancient. DOES NOT MATCH comp.hw. Match Level: 3 Master: >comp.hw.< comp. DOES NOT MATCH comp.hw. comp.hw. MATCHES comp.hw. comp.hw.new. MATCHES comp.hw. comp.hw.hw. MATCHES comp.hw. comp.sw.old. DOES NOT MATCH comp.hw. muse.hw.new. DOES NOT MATCH comp.hw. ancient. DOES NOT MATCH comp.hw.
Any thoughts!?
Thanks.
Edit: Added "comp." to the test array to complete that part of the picture... and have included the output produced by the code -OzB
In reply to I think regex Should Help Here... but How!? by ozboomer
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |