开发者

What is the meaning of this regular expression?

/\s/g

What is the meaning开发者_运维技巧 of the above regular expression?


It means search for a whitespace character. The /g means nothing in a single regex search.

Edit: You wanted a dissection. Here goes.

/

Start the regular expression.

\

A backslash is used to either escape special characters (that, on their own, would change how the regular expression operates, like how a + is used to denote "match one or more of the character right before me") or start a metacharacter. In this case, it's used to start a metacharacter:

s

Coupled with the backslash, the s means "match a whitespace character". Whitespace characters are spaces, tabs, newlines, and other such characters.

/

End the regular expression. OR DOES IT?

g

Hey what's going on here, CanSpice? I thought you said that / ended the regular expression? Well kind reader, this is what's called a "regular expression modifier". It means something like "search globally", and modifies the behaviour of the regular expression. In Perl, for example, it means something like "store the position of the match and start from that position again if we run the match again", so you can do things like:

my $x = "cat dog house";
while ($x =~ /(\w+)/g) {
    print "Word is $1, ends at position ", pos $x, "\n";
}

...which prints out:

Word is cat, ends at position 3
Word is dog, ends at position 7
Word is house, ends at position 13

For more, please see this tutorial.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜