PHP和正则表达式:检查字符串是否遵循带方括号的模式
I have no experience with regular expressions whatsoever, hence my question.
I have a string which should look like this:
[1,24,2,59]
As the string can be manipulated by the user and hence changed, I want to check whether it is still following the same organization pattern, and only containing numbers,square brackets and commas.
我没有任何正则表达式的经验,因此我的问题。 p>
我有一个字符串应该如下所示: p>
[1,24,2,59] p>
因为字符串可以被用户操纵 因此改变了,我想检查它是否仍然遵循相同的组织模式,并且只包含数字,方括号和逗号。 p> div>
You can use this regex in preg_match
to validate your input:
'/\[\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
'/^\[\d+(,\d+)*\]$/'
Same as the other answer, except it requires the whole string to match, otherwise a valid substring would suffice (e.g. "bla bla [1,3] bla bla")
'/^\[([1-9]\d+|\d)(,([1-9]\d+|\d))*\]$/'
Same, but numbers must have leading zeros removed, so "[12]" is OK but "[012]" is not.
'/^\s*\[\s*([1-9]\d+|\d)(\s*,\s*([1-9]\d+|\d))*\s*\]\s*$/'
Allows white spaces, e.g. " [ 1 , 12 , 12 ] " will be accepted but not "[1 2]".