What is this regular expression looking for [closed]

﹥>﹥吖頭↗ 提交于 2019-12-11 02:24:05

问题


preg_match ("/[-_^%&().A-Z0-9]/", $file)

By the looks of it, I can see that the tail end is Anything A-Z and 0-9, but not sure for the beginning. Because ^ is not escaped so it could be a literal "^" or evaluated to a NOT, and same goes with ".", "(" and ")". So I am just a bit confused. Does having things inside the optional [] means things are literalized?


回答1:


It just looks for one of the characters in the character class. I.e. one of:

  • Hyphen-minus, underscore, caret, percent, ampersant, parentheses, dot
  • Capital Latin letters
  • Arabic numerals

^ is only interpreted as negating a character class when at the very beginning of the class. . loses its special meaning inside character classes completely. So yes, in character classes many special regex characters are used literally. With exceptions, although the following list isn't exhaustive:

  • Hyphen-minus (-) indicates a range when between two other characters (i.e. not at the start or end).
  • The caret (^) as detailed above.
  • Predefined character classes (e.g. \w) can be used as well, which will form a union with the characters from that class. So your character class could be shortened to [-^%&().\w].



回答2:


^ only has a special meaning inside [] if it is the first character.
- only has a special meaning inside [] if is between two literal characters.
., ( and ) do not have a special meaning inside [].

Just reading the basic information in the docs would tell you all this.

The regex just matches one of the characters in the class.



来源:https://stackoverflow.com/questions/9466768/what-is-this-regular-expression-looking-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!