http://qs321.pair.com?node_id=726740


in reply to One regex construct to handle multiple string types

In case of input of "2L", \w* eats the "2". As input string does not have an optional dot, you are left with "L" as required by \S+, which is then printed.

Given the example strings, make preceding word letters AND the dot a single combination which is optional: m/ (?: \w+[.] )? (\S+) /x.

Replies are listed 'Best First'.
Re^2: One regex construct to handle multiple string types
by pobocks (Chaplain) on Nov 29, 2008 at 10:22 UTC
    Out of curiosity, can you point me toward the precise definition of '\w'? I'm not clear as to why it eats 2 instead of 2L.
    for(split(" ","tsuJ rehtonA lreP rekcaH")){print reverse . " "}print "\b.\n";
      It's not about \w, but about backtracking.

      \w* initially 'eats' 2L, but then is forced to ... well... put the 'L' back on the table to let \S have it.

      Hmm... maybe 'eating' is not the best image for what's going on with backtracking regexps...?

      :)

      Krambambuli
      ---

        AHHH! Thank you. Enlightenment is mine.

        "Must-match" versus "may-match" - separating the men from the boys of regex tug-o-war.

        for(split(" ","tsuJ rehtonA lreP rekcaH")){print reverse . " "}print "\b.\n";

      Precise definition depends on the language.

      Mastering Regular Expressions, 2nd Ed., Jeffery E. F. Friedll, published by O'Reilly characterizes\w in its "Common Metacharacters..." chapter, this way:

      Part-of_word character   Often the same as [a-zA-Z0-9_], although some ools omit the underscore, while others include all the extraalphanumerics characters in the locale. If Unicode is supported, \w usually refers to all alphanumerics (notable exception: Sun's Java regex package whose \w is exactly [a-zA-Z0-9_</c>).
      Regular Expressions Pocket Reference (also from O'Reilly) defines \w as:
      • \p{IsWord} for Perl
      • and as [A-Za-z0-9_] for Java.

      Regretably, the definition of \p{isWord} -- [_\p{L1}\p{Lu}\p{Lt}\p{Lo}\p{Nd} -- is, for me, almost impenetrable but Friedll's characterization may be as good as you'll get without deep study of perlretut and friends.