Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match word surronded by spaces OR at the end / beginning of the string using Perl regexp?

Tags:

regex

perl

I want to find sequences matching my regexp should they be in the middle of the string surrounded by spaces, in the end or beginning or be the only thing in a string.

Example: Let's assume the sequence 'qwe45rty' is what we are looking for. I want to be able to get positive on all of these strings:

'qwe45rty' 'qwe45rty blabla' 'smth qwe45rty blabla' 'smth qwe45rty' ' qwe45rty '

But none of these:

'aaqwe45rty' 'qwe45rtybb' 'aaqwe45rtybb'

Best what I came up with is smth like this:

if ( ($a =~ /\s+$re\s+/) or
     ($a =~ /^$re\s+/)   or
     ($a =~ /\s+$re$/)   or
     ($a =~ /^$re$/)        )
{
    # do stuff
}

which can't be the best way to do that :)

Any suggestions?

like image 473
bazzilic Avatar asked Nov 05 '12 04:11

bazzilic


1 Answers

You can do the or inside the regex:

/(^|\s+)qwe45rty(?=\s+|$)/

regex101

Note that the second group is a positive lookahead (?=) so it checks for whitespace, but doesn't consume it. That way the regex can match two consecutive occurrences of the string and give an accurate match count.

like image 93
AndreKR Avatar answered Sep 16 '22 21:09

AndreKR