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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With