Struggling With Perl Regular Expression
Regular Expressions February 16th, 2009I have a series of words followed by a pre-determined marker (say the letter x in this case) contained in a string.
$contents = 'test1x test!x test2x';
There is a need to extract a list of those words that contain only alphanumeric characters plus the marker, ‘x’. So obviously “test!x” not wanted.
If I run the following regex:
@filtered_list = ( $contents =~ /(?:[\w]+) /g );
Then I get the following list returned:
("test1x", "x", "test2x")
as opposed to a required list of
("test1x", "test2x")
The problem is with the 2nd item – it fails on the character “!” and just moves on to the next character when I really want to just stop right there and not return anything for this word.
I know I am just not seeing something completely obvious…
Thank you.
You nearly got it right. I tested this line:
@results=$contents=~/(\w+x)/g;
This returns a list of one or more alphanumeric characters, ([a-Z0-9_],) followed by the ‘x’ character. You forgot to add the explicit ‘x’.