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

后端 未结 2 1397
刺人心
刺人心 2020-12-19 23:11

Question

What does it mean when a regular expression is surrounded by @ symbols? Does that mean something different than being surround by slashes?

相关标签:
2条回答
  • 2020-12-19 23:40

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

    0 讨论(0)
  • 2020-12-19 23:41

    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 讨论(0)
提交回复
热议问题