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?

+3


source to share


2 answers


\w

matches only one character. You want the following:

/^\w+\s+\w+\z/

      



  • ^

    matches the beginning of the line.
  • \w+

    matches one of the "word" characters.
  • \s+

    matches one of the simpler characters.
  • \w+

    matches one of the "word" characters.
  • \z

    matches the end of the line.
+5


source


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*$/

+1


source







All Articles