说明
首先,正则表达式并不是最理想的解决方案,但我相信您有使用它的理由。
((\b[a-z]{1,}\b).*?)(\b\2\b)(.*)$
替换为: \1and\4
总结
此正则表达式将在字符串中找到两个相同的单词,并将第二个单词替换为and。
示例
现场演示
https://regex101.com/r/yG3yM6/2
示例文本
Green shirt green hat
Green shirt greenish hat
You are an artistically gifted musically gifted individual
示例匹配
Green shirt and hat
Green shirt greenish hat
You are an artistically gifted musically and individual
说明
NODE EXPLANATION
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
----------------------------------------------------------------------
[a-z]{1,} any character of: 'a' to 'z' (at least
1 times (matching the most amount
possible))
----------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
( group and capture to \3:
----------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
----------------------------------------------------------------------
\2 what was matched by capture \2
----------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
----------------------------------------------------------------------
) end of \3
----------------------------------------------------------------------
( group and capture to \4:
----------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
) end of \4
----------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
----------------------------------------------------------------------
额外积分
虽然在 OP 中没有解决,但如果有问题的单词使用非 a-z 字符,那么您可以将 [a-z] 替换为匹配非英语字符的 [a-z]|[^\x00-\x7F]。但是接下来我们需要将\b\2\b 更改为(?<=\s|^)\2(?=\s|$),这样我们才能确保正确匹配。
((\b(?:[a-z]|[^\x00-\x7F]){1,}\b).*?)((?<=\s|^)\2(?=\s|$))(.*)$
现场演示
https://regex101.com/r/wD8yF5/2