gpt4 book ai didi

php - 正则表达式匹配组不是由字母数字(\w)的前面忽略空格

转载 作者:行者123 更新时间:2023-12-04 08:02:44 26 4
gpt4 key购买 nike

我正在尝试匹配一个组,该组仅在匹配之前的第一个非空格字符不是字母数字字符时才匹配。
RegExp 我试过,先用\s* 消耗空格,然后回头检查\w:

(?<!\w)\s*\({\w+}\)
成功
Input:  this will = ({match})
Expected: ({match})
Actual: ({match})
失败,仍然匹配,前面是字母数字(忽略空格)
Input:  this should = not ({match})
Expected: -
Actual: ({match})
使用\s+ 而不是\s* 部分解决了它,但现在它至少需要一个不需要的空间!
(?<!\w)\s+\({\w+}\)
我一直在浏览互联网,但无法解决问题。任何人?

最佳答案

使用此解决方案(@horcrux@Wiktor Stribizew 建议的混合):

<?php

$regex = '/(?<![\w\s])\s*(\({\w+}\))/';
$string = 'this will = ({match})
this should = not ({match})';
preg_match_all($regex, $string, $matches);
var_dump($matches[1]);

?>
regex proof .
结果 :
array(1) {
[0]=>
string(9) "({match})"
}
PHP proof .
说明
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
[\w\s] any character of: word characters (a-z,
A-Z, 0-9, _), whitespace (\n, \r, \t,
\f, and " ")
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\( '('
--------------------------------------------------------------------------------
{ '{'
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
} '}'
--------------------------------------------------------------------------------
\) ')'
--------------------------------------------------------------------------------
) end of \1

关于php - 正则表达式匹配组不是由字母数字(\w)的前面忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66372088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com