ealeon
ealeon

Reputation: 12462

Why does adding the Perl /x switch stop my regex from matching?

I'm trying to match:

JOB: fruit 342 apples to get

The code matches:

$line =~ /^JOB: fruit (\d+) apples to get/

But, when I add the /x switch in:

$line =~ /^JOB: fruit (\d+) apples to get/x

It does not match.

I looked into the /x switch, and it says it just lets you do comments. I don't know why adding /x stops my regex from matching.

Upvotes: 4

Views: 2582

Answers (2)

tjd
tjd

Reputation: 4104

Part of allowing comments is also ignoring literal white space. Use \s or [ ] for spaces you wish to match.

For example

$line =~ /^                      #beginning of string
           JOB:[ ]fruit[ ]       #some literal text 
           (\d+)                 #capture digits to $1
           [ ]apples[ ]to[ ]get  #more literal text
         /x

Notice all those spaces before the beginning of the comments. It would stink if they counted....

Upvotes: 4

hmatt1
hmatt1

Reputation: 5159

The /x modifier tells Perl to ignore most whitespace that isn't escaped in the regex.

For example, let's just focus on apples to get. You could match it with:

$line =~ /apples to get/

But if you try:

$line =~ /apples to get/x

then Perl will ignore the spaces. So it would be like trying to match applestoget.

You can read more about it in perlre. They have this nice example of how you can use the modifier to make the code more readable.

 # Delete (most) C comments.
$program =~ s {
        /\* # Match the opening delimiter.
        .*? # Match a minimal number of characters.
        \*/ # Match the closing delimiter.
} []gsx;

They also mention how to match whitespace or # again while using the /x modifier.

Use of /x means that if you want real whitespace or # characters in the pattern (outside a bracketed character class, which is unaffected by /x), then you'll either have to escape them (using backslashes or \Q...\E ) or encode them using octal, hex, or \N{} escapes.

Upvotes: 9

Related Questions