duanbi7204 2014-01-31 20:27
浏览 62
已采纳

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

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:

(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.

I am still learning regular expressions, so any help is greatly appreciated, thanks.

  • 写回答

4条回答 默认 最新

  • doubang4881 2014-01-31 20:39
    关注

    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

    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. 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.

    Thanks to @sln for pointing that out.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题