Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring Whitespace with Regex(perl)

Tags:

regex

perl

I am using Perl Regular expressions. How would i go about ignoring white space and still perform a test to see if a string match. For example.

$var = "         hello     ";     #I want var to igonore whitespace and still match
if($var =~ m/hello/)
{



} 
like image 577
Zerobu Avatar asked Dec 22 '22 04:12

Zerobu


2 Answers

what you have there should match just fine. the regex will match any occurance of the pattern hello, so as long as it sees "hello" somewhere in $var it will match

On the other hand, if you want to be strict about what you ignore, you should anchor your string from start to end

if($var =~ m/^\s*hello\s*$/) {
}

and if you have multiple words in your pattern

if($var =~ m/^\s*hello\s+world\s*$/) {
}

\s* matches 0 or more whitespace, \s+ matches 1 or more white space. ^ matches the beginning of a line, and $ matches the end of a line.

like image 140
Charles Ma Avatar answered Dec 31 '22 20:12

Charles Ma


As other have said, Perl matches anywhere in the string, not the whole string. I found this confusing when I first started and I still get caught out. I try to teach myself to think about whether I need to look at the start of the line / whole string etc.

Another useful tip is use \b. This looks for word breaks so /\bbook\b/ matches

"book. "
"book "
"-book"

but not

"booking"
"ebook"
like image 45
justintime Avatar answered Dec 31 '22 21:12

justintime