开发者

What does it mean when a regular expression is surrounded by @ symbols?

Question

What does it mean when a regular expression is surrounded by @ symbols? Does that mean something different than being surround by slashes? What about when @x or @i are on the end? Now that I think about it, what do the surrounding slashes even mean?


Background

I saw this StackOverflow answer, posted by John Kugelman, in which he displays serious Regex skills.

Now, I'm used to seeing regexes surrounded by slashes as in

/^abc/

But he used a regex surrounded by @ symbols:

'@
        ^%
        (.{2})          # State, 2 chars
        ([^^]{0,12}.)   # City, 13 chars, delimited by ^
        ([^^]{0,34}.)   # Name, 35 chars, delimited by ^
        ([^^]{0,28}.)   # Address, 29 chars, delimited by ^
        \?$
 @x'

In fact, it seems to be in the format:

@^abc@x

In the process of trying to google what that means (it's a tough question to google!), I also saw the format:

@^abc@i

It's clear the x开发者_如何学编程 and the i are not matched characters.

So what does it all mean???

Thanks in advance for any and all responses,

-gMale


The surrounding slashes are just the regex delimiters. You can use any character (afaik) to do that - the most commonly used is the /, other I've seen somewhat commonly used is #

So in other words, @whatever@i is essentially the same as /whatever/i (i is modifier for a case-insensitive match)

The reason you might want to use something else than the / is if your regex contains the character. You avoid having to escape it, similar to using '' for strings instead of "".


Found this from a "Related" link.

The delimiter can be any character that is not alphanumeric, whitespace or a backslash character.

/ is the most commonly used delimiter, since it is closely associated with regex literals, for instance in JavaScript where they are the only valid delimiter. However, any symbol can be used.

I have seen people use ~, #, @, even ! to delimit their regexes in a way that avoids using symbols that are also in the regex. Personally I find this ridiculous.

A lesser-known fact is that you can use a matching pair of brackets to delimit a regex in PHP. This has the tremendous advantage of having an obvious difference between the closing delimiter, and the symbol showing up in the pattern, and therefore don't need any escaping. My personal preference is this:

(^abc)i

By using parentheses, I remind myself that in a match, $m[0] is always the full match, and the subpatterns start at $m[1].

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜