Perl regexp extract two consecutive words
I am trying to extract strings of two words separated by one or more spaces from a list. Example:
@a=("aaa12:.", "lala lulu", "erwer", ",", "lala loqw asqwd", "asdas sadsad", "asasd| asq");
@b=grep {/\w+\s+\w+/} @a;
it gives me
'lala lulu',
'lala loqw asqwd',
'asdas sadsad'
but I dont want grep one with three words ...
I tried @b=grep {/^\w\s+\w$/}
but didn't get any matches later. Should be simple, but I just don't get it. What regex do I need here?
source to share
I tried @b=grep {/^\w\s+\w$/} but then I don't get any matches
The only reason it doesn't work is because you left the
start / end quantifier :
/^\w\s+\w$/
^ ^
where would it work fine if it were /^\w+\s+\w+$/
The best way to do this, however, is to add some flexibility with spaces: /^\s*\w+\s+\w+\s*$/
source to share