Regexp Syntax trouble

Posted by tobiassjosten on Wed 27 Apr 2005 08:41 PM — 4 posts, 19,311 views.

Sweden #0
I'm trying to match these lines:
You quickly eat a wormwood root.
You quickly eat a nightshade root.
You quickly eat a galingale flower.
You quickly eat a piece of kelp.
You quickly eat a mandrake root.
You quickly eat an orphine seed.
You quickly eat a maidenhair leaf.	
You quickly eat some hyssop stem.
You quickly eat a juniper berry.

And I want a wildcards["herb"] command being sent to a function of mine, containing the actual herb I ate. The herbs are: wormwood, galingale, kelp, mandrake, orphine, maidenhair, hyssop and juniper. Is this even posible with one line of regexp? I could do it in two triggers, one seperate for the kelp-line, but that'd look oogley. :P So far I've got:
You quickly eat (a|an|some)(.|piece of.)(?P<herb>\w+)(\.|root\.|flower\.|seed\.|leaf\.|stem\.|berry\.)$

But it doesn't react, at all..
USA #1
^You quickly eat (an?|some)( piece of)? (?P<herb>\w+)( (root|flower|seed|leaf|stem|berry))?\.$

You forgot to allow for a space between a/an/some and piece of and the herb and your list of types (stem, etc).
But that Regexp up there works, and is more efficient (doesn't have all the redundant periods, or the alternate method of doing piece of. Get comfortable with '?' for optional it is indeed your friend).
Amended on Wed 27 Apr 2005 09:12 PM by Flannel
Sweden #2
You're a savior! ;) So, the ?-mark matches .. what again?
USA #3
the ? mark tells whatever is IMMEDIATELY infront of it to match 0 or 1 times.

so like, "an?" match a or an (1 or 0 'n's), and then when you do it on a group like ( piece of)? it says "look for the group ' piece of 0 or 1 times".
The same thing at the end (the group directly infront of the ? includes the group of alternates, as well as the space infront of them).

Quantifier rundown:
* is 0 or more, + is 1 or more, ? is 0 or 1
so, .* is equivalent to .+? (0 or 1 of 1 or more items)
You can do the same with brackets: {0,} (*), {1,} (+), {0,1} (?), and then that allows you to get even more specific with things like: {3,6} (between three or six).