简体   繁体   English

快速PHP正则表达式,用于数字格式

[英]Quick PHP regex for digit format

I just spent hours figuring out how to write a regular expression in PHP that I need to only allow the following format of a string to pass: 我花了几个小时弄清楚如何在PHP中编写正则表达式,只需要传递以下格式的字符串即可:

(any digit)_(any digit)

which would look like: 看起来像:

219211_2

so far I tried a lot of combinations, I think this one was the closest to the solution: 到目前为止,我尝试了很多组合,我认为这是最接近解决方案的组合:

/(\\d+)(_)(\\d+)/

also if there was a way to limit the range of the last number (the one after the underline) to a certain amount of digits (ex. maximal 12 digits), that would be nice. 同样,如果有一种方法可以将最后一个数字(下划线之后的数字)的范围限制为一定数量的数字(例如最大12个数字),那也不错。

I am still learning regular expressions, so any help is greatly appreciated, thanks. 我仍在学习正则表达式,因此非常感谢您的帮助。

You don't need double escaping \\\\d in PHP. 您不需要在PHP中双转义\\\\d

Use this regex: 使用此正则表达式:

"/^(\d+)_(\d{1,12})$/"
  • \\d{1,12} will match 1 to 12 digist \\d{1,12}将匹配1到12位专家
  • Better to use line start/end anchors to avoid matching unexpected input 更好地使用行开始/结束锚,以避免匹配意外输入

The following: 下列:

\d+_\d{1,12}(?!\d)

Will match "anywhere in the string". 将匹配“字符串中的任何地方”。 If you need to have it either "at the start", "at the end" or "this is the whole thing", then you will want to modify it with anchors 如果您需要“在开始时”,“在结束时”或“这就是全部”,那么您将需要使用锚点对其进行修改

^\d+_\d{1,12}(?!d)      - must be at the start
\d+_\d{1,12}$           - must be at the end
^\d+_\d{1,12}$          - must be the entire string

demo: http://regex101.com/r/jG0eZ7 演示: http : //regex101.com/r/jG0eZ7

Explanation: 说明:

\d+      - at least one digit
_        - literal underscore
\d{1,12} - between 1 and 12 digits
(?!\d)   - followed by "something that is not a digit" (negative lookahead)

The last thing is important otherwise it will match the first 12 and ignore the 13th. 最后一点很重要,否则它将与前12个匹配并忽略第13个。 If your number happens to be at the end of the string and you used the form I originally had [^\\d] it would fail to match in that specific case. 如果您的数字恰好在字符串的末尾,并且您使用的是我最初的格式[^\\d]则在这种情况下将无法匹配。

Thanks to @sln for pointing that out. 感谢@sln指出这一点。

Try this: 尝试这个:

$regex= '~^/(\d+)_(\d+)$~';
$input= '219211_2';
if (preg_match($regex, $input, $result)) {
 print_r($result);
}

只需尝试以下正则表达式即可:

^(\d+)_(\d{1,12})$

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

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