简体   繁体   English

preg_match和regex - 允许或排除字符

[英]preg_match and regex - allow or exclude characters

I have problem with allowing specified characters in preg_match. 我在preg_match中允许指定字符时遇到问题。 I've tried making following pattern: /^[A-Za-z0-9 !@#$%&()-_\\[\\]:;\\"'|,.\\?\\/]/ Right now it allows everything, even * which is not there. 我尝试过以下模式: /^[A-Za-z0-9 !@#$%&()-_\\[\\]:;\\"'|,.\\?\\/]/现在它允许一切,甚至*都不存在。

I know that there's this rule that before regex specified characters I have to put "\\" before character. 我知道有这个规则,在正则表达式指定字符之前我必须在字符前加上"\\" Correct me if I'm wrong. 如果我错了纠正我。

Can someone explain me how does this work? 有人可以解释我这是如何工作的?

I want to allow this chars: AZ az 0-9 !@#$%&()-_[]:;"'|,.?/ (and of course spaces) 我想允许这个字符:AZ az 0-9!@#$%&()-_ []:;“'|,。?/(当然还有空格)

And exclude this: ~`^*+={}<>\\ 并排除这个:~` ^ * + = {} <> \\

An unescaped hyphen needs to be at first or last position in a character class or it needs to be escaped. 未转义的连字符需要位于字符类的第一个或最后一个位置,否则需要进行转义。 Otherwise it is considered a range. 否则它被认为是一个范围。 So use: 所以使用:

/^[A-Za-z0-9 !@#$%&()_\[\]:;\"'|,.\?\/-]/

In your regex /^[A-Za-z0-9 !@#$%&()-_\\[\\]:;\\"'|,.\\?\\/]/ where - is in the middle of and ) (ASCII: 41) and _ (ASCII: 95), hence matching all the characters in this range. 在您正则表达式/^[A-Za-z0-9 !@#$%&()-_\\[\\]:;\\"'|,.\\?\\/]/哪里-是在中部和) (ASCII:41)和_ (ASCII:95),因此匹配此范围内的所有字符。

Also you need to use anchors to match entire input: 您还需要使用锚点来匹配整个输入:

/^[A-Za-z0-9 !@#$%&()_\[\]:;\"'|,.\?\/-]+$/

This part )-_ in the character class is a range of characters. 这部分)-_在字符类中是一系列字符。
From ) to _ . )_

You probably should escape the dash .. )\\-_ then its just a character. 你可能应该逃脱破折号.. )\\-_然后它只是一个角色。

  41    29  )       73  49  I      
  42    2A  *       74  4A  J      
  43    2B  +       75  4B  K      
  44    2C  ,       76  4C  L      
  45    2D  -       77  4D  M      
  46    2E  .       78  4E  N      
  47    2F  /       79  4F  O      
  48    30  0       80  50  P      
  49    31  1       81  51  Q      
  50    32  2       82  52  R      
  51    33  3       83  53  S      
  52    34  4       84  54  T      
  53    35  5       85  55  U      
  54    36  6       86  56  V      
  55    37  7       87  57  W      
  56    38  8       88  58  X      
  57    39  9       89  59  Y      
  58    3A  :       90  5A  Z      
  59    3B  ;       91  5B  [      
  60    3C  <       92  5C  \      
  61    3D  =       93  5D  ]      
  62    3E  >       94  5E  ^      
  63    3F  ?       95  5F  _    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM