How to combine surronded word with spaces OR at the end / beginning of a line using Perl regexp?

I want to find sequences matching my regular expression if they are in the middle of a line surrounded by spaces, at the end or at the beginning, or will be the only thing in the line.

Example: Suppose the sequence 'qwe45rty' is what we are looking for. I want to be able to get a positive result on all of these lines:

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

But not one of them:

'aaqwe45rty' 'qwe45rtybb' 'aaqwe45rtybb'

The best I came up with is something like this:

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

which may not be the best way to do this :)

Any suggestions?

+6
source share
3 answers

You can do either inside the regex:

 /(^|\s+)qwe45rty(\s+|$)/ 
+17
source

Try to find the problem in a different direction. To say that something can match a space, or nothing means to say that it cannot match a character without spaces:

 (?<!\S)qwe45rty(?!\S) 

A little shift in perspective, and regular expression actually writes itself.

+6
source

Try the following:

 $a =~ /(?:\A|\s)$re(?:\s|\Z)/; 

For instance:

 use strict; use warnings; my $re = 'qwe45rty'; while (<DATA>) { chomp; print "'$_': Match? " . ( /(?:\A|\s)$re(?:\s|\Z)/ ? 'Yes' : 'No' ) . "\n"; } __DATA__ qwe45rty qwe45rty blabla smth qwe45rty blabla smth qwe45rty qwe45rty aaqwe45rty qwe45rtybb aaqwe45rtybb 

Conclusion:

 'qwe45rty': Match? Yes 'qwe45rty blabla': Match? Yes 'smth qwe45rty blabla': Match? Yes 'smth qwe45rty': Match? Yes ' qwe45rty ': Match? Yes 'aaqwe45rty': Match? No 'qwe45rtybb': Match? No 'aaqwe45rtybb': Match? No 
+1
source

All Articles