tags:

views:

57

answers:

3

Hello, 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/)
{



} 
+4  A: 

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.

Charles Ma
A: 

/^\s*hello\s*$/

Einstein
A: 

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"
justintime