PHP和正则表达式:检查字符串是否遵循带方括号的模式

时间:2014-02-01 13:40:35

标签: php regex

我没有任何正则表达式的经验,因此我的问题。

我有一个字符串应该是这样的:

[1,24,2,59]

由于字符串可以被用户操纵并因此被更改,我想检查它是否仍然遵循相同的组织模式,并且只包含数字,方括号和逗号。

2 个答案:

答案 0 :(得分:0)

您可以在preg_match中使用此正则表达式验证您的输入:

'/\[\d+(,\d+)*\]/'

\[ matches the character [ literally
\d+ match a digit [0-9]
Quantifier: Between one and unlimited times, as many times as possible, giving back as
  needed [greedy]
1st Capturing group (,\d+)*
Quantifier: Between zero and unlimited times, as many times as possible, giving back as 
  needed [greedy]
Note: A repeated capturing group will only capture the last iteration. Put a capturing 
  group around the repeated group to capture all iterations or use a non-capturing group 
   instead if you're not interested in the data
, matches the character , literally
\d+ match a digit [0-9]
Quantifier: Between one and unlimited times, as many times as possible, giving back as 
  needed [greedy]
\] matches the character ] literally

答案 1 :(得分:0)

'/^\[\d+(,\d+)*\]$/'

与其他答案相同,除了它要求整个字符串匹配,否则一个有效的子字符串就足够了(例如“bla bla [1,3] bla bla”)

'/^\[([1-9]\d+|\d)(,([1-9]\d+|\d))*\]$/'

相同,但数字必须删除前导零,因此“[12]”可以,但“[012]”不是。

'/^\s*\[\s*([1-9]\d+|\d)(\s*,\s*([1-9]\d+|\d))*\s*\]\s*$/'

允许空格,例如“[1,2,12]”将被接受但不是“[1 2]”。