问题描述
使用 PCRE,我只想捕获一行中的所有数字,但前提是该行内的任何位置都存在某个字符串(例如STRING99").
Using PCRE, I want to capture only and all digits in a single line, but only if a certain string (say "STRING99") is present anywhere within that line.
例如,考虑以下两种情况:
For example, consider these two cases:
a1 STRING99 2b c3d
a1 2b c3d
在第一种情况下,我希望结果是19923".在第二种情况下,我想要一个空结果.
In the first case, I want the result to be "19923".In the second case, I want an empty result.
我不确定这是否可行.它可能适用于可变长度的lookbehind,但在PCRE 中不受支持.此外,类似于 (?=.*STRING99.*$)(\D|(\d))*
的东西会起作用,但是重复捕获组只会捕获最后一次迭代",意思是第二个捕获组只捕获最后一位数字.我找不到解决方法.
I am not sure this is possible. It might work with a variable-length lookbehind, but this is not supported in PCRE. Furthermore, something like (?=.*STRING99.*$)(\D|(\d))*
WOULD work, but "a repeated capturing group will only capture the last iteration", meaning the second capturing group only captures the last digit. I am unable to find a workaround for this.
(这显然不难通过 2 个连续的 Regex 操作实现,但我希望在一个公式中实现.)
(This is obviously not hard to achieve with 2 consecutive Regex operations, but I want it in one formula.)
推荐答案
您可以在 preg_replace
中使用这个 PCRE 正则表达式:
You may use this PCRE regex in preg_replace
:
^(?!.*STRING99).*(*SKIP)|\D+
正则表达式详情:
^
:开始(?!.*STRING99)
:Lokahead 检查输入中是否有STRING99
.*(*SKIP)
:匹配输入的其余部分直到结束并跳过它|
:或\D+
:匹配 1+ 个非数字
^
: Start(?!.*STRING99)
: Lokahead to check if we haveSTRING99
anywhere in input.*(*SKIP)
: Match rest of the input till end and skip it|
: OR\D+
: Match 1+ non-digit
PHP 代码:
$repl = preg_replace('~^(?!.*STRING99).*(*SKIP)|\D+~', '', $str);
这篇关于正则表达式 (PCRE):以存在字符串为条件匹配所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!