Match several words


This won't match as there are more words

examples/regex2/matching_word_fails.p6
use v6;

my $words = 'foo, bar, moo';

if $words ~~ m/^ \w+ $/ {
	say 'no match';
}


so we need to add a regex for the separators , and spaces and we put the whole thing in a [] which is a (non-capturing) grouping, apply a quantifier on that but we also need to add another word matching regex for the last word

examples/regex2/match_several_words.p6
use v6;

my $words = 'foo, bar, moo';

if $words ~~ m/^ [\w+\,\s*]* \w+ $/ {
	say 'match words';
}


It could be also written this way: The generic quantifier can also get a separator on its right hand side.

examples/regex2/match_several_words2.p6
use v6;

my $words = 'foo, bar, moo';

if $words ~~ m/^ [\w+] ** [\,\s*] $/ {
	say 'match words again';
}


Copyright 2006, 2007, 2008, 2009, 2010 Gabor Szabo http://szabgab.com/ Index | TOC
If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed