寻找一个检测单个字符(特定)的正则表达式模式,但是当它是双精度或三进制时忽略它。

abcde <- looking for this (c's separated by another character)
abccdce <- not this (immediately repeating c's)

我想替换单个字符,但在重复时忽略它们。

所需的结果(用“ FOO”替换单个“ c”)

abcde -> abFOOde
abccdce -> abccdce
abcdeabccde ->abFOOdeabccde

提示:我知道相反的做法-取代双打而忽略单打

$pattern = '/c\1{1}/x';
$replacement = 'FOO';
preg_replace($pattern, $replacement, $text);

===============>>#1 票数:2

您可以为此使用环顾

(?<!c)c(?!c)

这意味着匹配c如果在任一侧都没有被c包围。

正则表达式分解:

(?<!c)  # negative lookbehind to fail the match if previous position as c
c       # match literal c
(?!c)   # negative lookahead to fail the match if next position as c

码:

$repl = preg_replace('/(?<!c)c(?!c)/', 'FOO', $text);

  ask by fatfish translate from so

未解决问题?本站智能推荐: