in reply to Regex - Matching prefixes of a word

What about reversing the approach?

Instead of making a regex that matches any $word that is a prefix of 'angle', why don't use $word as a regex:

my @keywords = qw / angle offset fire torpedo /; my @match = grep $_ =~ /^$word/ @keywords;

If you previously ensured that word is a word (i.e. /\w+/), @match will give you all the keywords that partially match $word. If @match == 0, no match; if @match == 1, exact match; if @match > 1, word is ambiguous.

Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Replies are listed 'Best First'.
Re^2: Regex - Matching prefixes of a word
by SuicideJunkie (Vicar) on Jul 24, 2009 at 16:41 UTC

    I actually did use that pattern in a few limited other places in the code, but as far as I see, it can only be practically used after you've parsed out a parameter and want to know what things that specific parameter matches.

    >replace officer sci with Spock if ($command =~ /^(?:replace\s+)?officer\s+([a-z]+)\s+with ([a-z]+)/i) { $crewStation = $1; $newOfficerName = $2; $officer->{science} = $newOfficerName if ('science' =~ /$crewStation +/); ... }

    I don't see how that trick could be used like a subexpression to help out the first command recognition regex. (Being usable as a subexpression is critical)

    However, I do very much like the idea of grepping over a list of keywords in order to make synonyms trivial to add.