2011-11-12 145 views
4

我需要在更长的字母数字数据字符串中识别子字符串“X.123”和/或“X.8”。例如:使用RegEx从字母数字字符串中提取数字

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 )

帮助非常感谢!

+2

+1的飞牛;) – Beat

回答

4

\ b在这种背景不错,我会用这样的:

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

这很好,谢谢。 –

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]; 
} 
+0

无法让这个工作。 –

+0

@acoder您正在使用哪种正则表达式引擎? – FailedDev

+0

这是一个PHP脚本。 –