使用正则表达式从包含字母和数字的字符串中提取数字

4

我需要在一个更长的字母数字数据串中识别子字符串'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)。

非常感谢您的帮助!

3个回答

4
\b在这个上下文中非常不错,我会像这样使用它:
/\bX\.\d{1,4}\b/

2

试试这个:

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

1

我会使用这个。在开头使用\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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接