使用RegEx从字母数字字符串中提取数字

时间:2022-12-27 10:21:15

I need to identify substring 'X.123' and/or 'X.8' in a longer string of alphanumeric data. Ex:

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

How would I exclude the second and third instance? This is what I've come up with so far to get the "X.123" part:

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

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

I'm not exactly sure how to make the expression stop at any non-numeric character (ex: X124C78)

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

Help greatly appreciated!

非常感谢!

3 个解决方案

#1


4  

The \b is nice in this context, i would use it like this:

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

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

#2


2  

Try this:

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

#3


1  

I would use this. The \b in the start helps avoiding matches such as AX.123

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

#1


4  

The \b is nice in this context, i would use it like this:

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

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

#2


2  

Try this:

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

#3


1  

I would use this. The \b in the start helps avoiding matches such as AX.123

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