开发者

Ignoring Whitespace with 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/)
{



} 


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.


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"


This regex is a little unrelated but if you wanted to concatenate all of the whitespaces from your string before passing it through the if.

s/[\h\v]+/ /g;


/^\shello\s$/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜