【问题标题】:Using RegEx to extract number from alphanumeric string使用 RegEx 从字母数字字符串中提取数字
【发布时间】:2011-11-12 19:35:14
【问题描述】:

我需要在较长的字母数字数据字符串中识别子字符串“X.123”和/或“X.8”。例如:

A cow flew over the moon in the X.123 module, not the X.124.3 module, 
and certainly not the X.125C78 module.  The cow poo-pooed the X.8 module.

如何排除第二个和第三个实例?到目前为止,这是我想出的获得“X.123”部分的方法:

/[X][\.][0-9]{1,4}/

我不确定如何让表达式在任何非数字字符处停止(例如:X124C78)

帮助不胜感激!

【问题讨论】:

  • 飞牛+1 ;)

标签: regex


【解决方案1】:

\b 在这种情况下很好,我会这样使用它:

/\bX\.\d{1,4}\b/

【讨论】:

    【解决方案2】:

    试试这个:

    /X\.[0-9]{1,4}(?=\s|$)/
    

    【讨论】:

      【解决方案3】:

      我会用这个。开头的\b 有助于避免匹配,例如AX.123

      /\bX\.\d+(?=\s|$)/
      
      preg_match_all('/\bX\.\d+(?=\s|$)/', $subject, $result, PREG_PATTERN_ORDER);
      for ($i = 0; $i < count($result[0]); $i++) {
          # Matched text = $result[0][$i];
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-10
        • 2017-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-24
        相关资源
        最近更新 更多