Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^3: Regular Expression Hiccup

by AnomalousMonk (Archbishop)
on May 04, 2015 at 21:46 UTC ( [id://1125640]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Regular Expression Hiccup
in thread Regular Expression Hiccup

... "X-ray" simply fails.

What others have written remains true: a '-' (dash; hyphen) character is not the same as (and will not match) a ' ' (space) character. (Also pay attention to hdb's reply below (update: among others) concerning case-insensitive matching.) Consider these matches to get a feel for regex matching:

c:\@Work\Perl\monks>perl -wMstrict -le "my @X = ('aX-raya', 'aX raya', 'aXraya', 'axraya', 'X Ray', 'aXYraya' +); ;; print 'case-sensitive matching:'; for my $s (@X) { printf qq{'$s' -> }; if ($s =~ m{ X [- ]? ray }xms) { print 'match'; } else { print 'NO match'; } } ;; print 'case-INsensitive matching:'; for my $s (@X) { printf qq{'$s' -> }; if ($s =~ m{ (?i) X [- ]? ray }xms) { print 'match'; } else { print 'NO match'; } } " case-sensitive matching: 'aX-raya' -> match 'aX raya' -> match 'aXraya' -> match 'axraya' -> NO match 'X Ray' -> NO match 'aXYraya' -> NO match case-INsensitive matching: 'aX-raya' -> match 'aX raya' -> match 'aXraya' -> match 'axraya' -> match 'X Ray' -> match 'aXYraya' -> NO match

Contrast the use of  [- ]? with  . (dot) as a placeholder to match anything at all:

c:\@Work\Perl\monks>perl -wMstrict -le "my @X = ('aX-raya', 'aX raya', 'aXraya', 'axraya', 'X Ray', 'aXYraya' +); ;; print 'placeholder matching:'; for my $s (@X) { printf qq{'$s' -> }; if ($s =~ m{ X . ray }xms) { print 'match'; } else { print 'NO match'; } } " placeholder matching: 'aX-raya' -> match 'aX raya' -> match 'aXraya' -> NO match 'axraya' -> NO match 'X Ray' -> NO match 'aXYraya' -> match
In general, it's better to match exactly what you want.

Please see the Perl regex documentation perlre, perlretut, perlrequick, and various regex tutorials on Perlmonks.


Give a man a fish:  <%-(-(-(-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1125640]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-25 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found