正则表达式 - 在某个单词之后匹配4位数字作为完全匹配而不是组

时间:2022-07-26 19:29:20

I'm having hard time trying to figure out regular expression that will extract 4 digits long number after certain word as full match.

我很难找出正则表达式,它会在某个单词作为完全匹配后提取4位数的长数字。

Here is the text:

这是文字:

FV 7017 FOR SOMETHING 1076,33 USD.

and here is my regular expression to extract the 4 digits number:

这是我的正则表达式提取4位数字:

/FV (\d{4,})/

That will result in:

这将导致:

Full match  = `FV 7017`
Group 1 match = `7017`

Is it possible to exclude that "FV" word using regex to have that result as full match?

是否可以使用正则表达式排除“FV”单词以使结果完全匹配?

2 个解决方案

#1


0  

4 steps faster than a positive lookbehind, is to use \K to restart the fullstring match.

比正面lookbehind快4步,就是使用\ K来重启全字符串匹配。

/FV \K\d{4}/

Pattern Demo

模式演示

PHP Implementation:

PHP实现:

$string='FV 7017 FOR SOMETHING 1076,33 USD.';
echo preg_match('/FV \K\d{4}/',$string,$out)?$out[0]:'fail';
// output: 7017

#2


1  

Yes, it's possible in PHP: just use so-called positive lookbehind assertion (demo)

是的,它可以在PHP中使用:只需使用所谓的正向lookbehind断言(演示)

/(?<=FV )\d{4,}/

It reads as "match four or more digits, but only if they're preceded by 'FV ' sequence".

它读作“匹配四个或更多数字,但前提是它们前面是'FV'序列”。

#1


0  

4 steps faster than a positive lookbehind, is to use \K to restart the fullstring match.

比正面lookbehind快4步,就是使用\ K来重启全字符串匹配。

/FV \K\d{4}/

Pattern Demo

模式演示

PHP Implementation:

PHP实现:

$string='FV 7017 FOR SOMETHING 1076,33 USD.';
echo preg_match('/FV \K\d{4}/',$string,$out)?$out[0]:'fail';
// output: 7017

#2


1  

Yes, it's possible in PHP: just use so-called positive lookbehind assertion (demo)

是的,它可以在PHP中使用:只需使用所谓的正向lookbehind断言(演示)

/(?<=FV )\d{4,}/

It reads as "match four or more digits, but only if they're preceded by 'FV ' sequence".

它读作“匹配四个或更多数字,但前提是它们前面是'FV'序列”。