Re: new for regular expression in Perl




----- Original Message ----- From: "chen li" <chen_li3@xxxxxxxxx>



Hi all,

Here is my problem:

my $string="chen schen";

I want to use regular expression to find the exact
match in the string. So when I want to match "chen" I
expect "chen" only.
But  use the following line I get both "chen" and
"schen" at the same time.
$string=~/chen/g;

How do I get what I expect?

Hi Chen

You can get the results by adding a \b before and after your reg expression. \b is a boundary between a word and a non-word character. (A word character is a-z, A-Z, 0-9, or underscore, _).So, for your example, schen wouldn't match then because the 's' preceding 'c' is a word character and so the \b wouldn't be true. But, it would match chen because the (non) character (beginning of the string) preceding the 'c' would make \b true.

$string=~/\bchen\b/g;

MATCH
"chen "
"#chen"
"here is a chen and another chen"
"chen's"    (the apostrophy is a non-word char)

NO MATCH
"schen"
"chens"

Chris


.