duanoucuo7045 2011-01-22 13:22
浏览 50
已采纳

匹配正则表达式中的固定格式数字和可选字符串

Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo "bad format!";
  }

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.

  • 写回答

2条回答 默认 最新

  • dou70260 2011-01-22 13:28
    关注

    Try this:

    /^\d{2}:\d{2}(?:\s?[AP]M)?$/
    

    Here the last part (?:\s?[AP]M)? is an optional, non-capturing group that may start with an optional whitespace character and is then followed by either AM or PM.

    For the number ranges replace the first \d{2} by (?:0\d|1[012]) and the second by (?:[0-5]\d|60).

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

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?