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

Re^2: why is regex not matching final character?

by fiverivers (Novice)
on May 07, 2012 at 08:19 UTC ( #969216=note: print w/replies, xml ) Need Help??

in reply to Re: why is regex not matching final character?
in thread why is regex not matching final character?

That must be correct. I thought \w would gobble up the whole table name first and [^\s] would stop the gobbling at the first space. But it is matching as much as possible and excluding the last non-space character because it is not in the brackets as you said.

Replies are listed 'Best First'.
Re^3: why is regex not matching final character?
by moritz (Cardinal) on May 07, 2012 at 08:32 UTC

    [...] always matches exactly one character, so the previous \w* has to backtrack and give up one character, in order for the whole match to succeed.

    By the way you can write [^\s] simpler as \S.

    The problem here is \w and \S can match the same characters, so if you match a sequence of \w and \S, the rules about which matches what are governed by the backtracking rules of the regex engine, not by what your intuition expects.

    If you want to match a word, and then want to allow non-word but also non-whitespace characters, you can say (\w+)\s*. The \s* allows empty non-whitespace character sequences too. The regex engine greedily matches as many characters as possible with the \w+, and happily leaves \s* to match the empty string if the following character is a space.

      sounds like you know your regexes. Thinking about the whole thing again all I need is the code below because \w does not match spaces so will stop at the first space.

      if ($line =~ m/^update\ (\w*)/){ print $1."\n"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://969216]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (9)
As of 2017-11-23 22:17 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (343 votes). Check out past polls.