What literal characters should be escaped in a regex?

前端 未结 5 1450
予麋鹿
予麋鹿 2020-11-30 01:47

I just wrote a regex for use with the php function preg_match that contains the following part:

[\\w-.]

To match any word char

5条回答
  •  余生分开走
    2020-11-30 02:42

    The full stop loses its meta meaning in the character class.

    The - has special meaning in the character class. If it isn't placed at the start or at the end of the square brackets, it must be escaped. Otherwise it denotes a character range (A-Z).

    You triggered another special case however. [\w-.] works because \w does not denote a single character. As such PCRE can not possibly create a character range. \w is a possibly non-coherent class of symbols, so there is no end-character which could be used to create the range Z till .. Also the full stop . would preceed the first ascii character a that \w could match. There is no range constructable. Hencewhy - worked without escaping for you.

提交回复
热议问题