我需要有一个正则表达式,它找到一个后跟不同字符的字符。平均排除双倍甚至多个相同的字符。
例如,当我需要从字符串'e'
中找到"need only single characteeer"
个字符时,意味着会在每个字词细分上找到'e'
,如下所示:
"need"
>不匹配,因为它有两倍'e'
"only"
>不匹配,因为没有'e'
"single"
>匹配因为只有一个'e'
"characteeer"
>不匹配,因为有多个'e'
不确定是否可能。任何答案或评论将受到高度赞赏。提前谢谢。
更新
也许我上面的问题仍然含糊不清。实际上我只需要找到'e'
字符而不是单词。我要用双字符替换它。所以已经有双重角色的那个不会被取代。
主要目的是将'e'
替换为'ee'
。但是,'ee'
或'eee'
已经或甚至更多'e'
的那个将不受影响。
答案 0 :(得分:5)
更新:
(?<!e)e(?!e)
将匹配e而不是负面的lookbehind以防止前面的e和负面的预测阻止跟随e。
\b(([A-Za-z])(?!\2))+\b
将匹配一个单词(A-Za-Z之间的一个或多个字符的序列),带有负向前瞻,以防止后续字符与上一个匹配,组2或使用非捕获组相同。
/\b(?:([A-Za-z])(?!\1))+\b/g
然而only
会匹配,因为它不包含重复的字符。
匹配a word containing e
but no ee
/(?<![a-z])(?=[a-z]*e)(?![a-z]*ee)[a-z]+/gi
答案 1 :(得分:2)
/\b([a-df-z]*e[a-df-z]*)\b\s*/g
如果需要,您可以添加不区分大小写的/i
。
<强>解释强>
/ : regex delimiter
\b : word boundary
( : start group 1
[a-df-z]* : 0 or more letter that is not "e"
e : 1 letter "e"
[a-df-z]* : 0 or more letter that is not "e"
) : end group 1
\b : word boundary
\s* : 0 or more spaces
/g : regex delimiter, global flag
由于您没有提供您正在使用的语言,因此这是一个perl脚本:
my $str = "need only single characteeer";
my @list = $str =~ /\b([a-df-z]*e[a-df-z]*)\b\s*/g;
say Dumper\@list;
<强>输出:强>
$VAR1 = [
'single'
];
一个php脚本:
$str = "need only single characteeer";
preg_match_all("/\b([a-df-z]*e[a-df-z]*)\b\s*/", $str, $match);
print_r($match);
<强>输出:强>
Array
(
[0] => Array
(
[1] => single
)
[1] => Array
(
[1] => single
)
)