正则表达式 - 匹配所有单词但只匹配唯一单词一次 [英] Regular expression - match all words but match unique words only once
问题描述
是否可以使用正则表达式匹配所有单词但只匹配唯一单词一次?我知道还有其他方法可以做到这一点,但我很想知道使用正则表达式是否可行.
Is it possible to use a regular expression to match all words but match unique words only once? I am aware there are other ways of doing this however I'm interested in knowing if this is possible with the use of a regular expression.
例如我目前有以下表达式:
For example I currently have the following expression:
(\w+\b)(?!.*\1)
和以下字符串:
glass shoes door window door glasses. window glasses
在大多数情况下,该表达式有效并匹配以下单词:
For the most part the expression works and matches the following words:
shoes
door
window
glasses
这有两个问题:
在带有glass"的glasses"上匹配子字符串,这是不正确的.
A match for a substring is being made on "glasses" with "glass", this is incorrect.
眼镜"和眼镜".应该匹配,但目前不匹配.
"glasses" and "glasses." should match but currently do not.
最终匹配应该是:
shoes
door
window
glasses
glass
推荐答案
很接近,只是看了下负lookahead中的\b
Pretty close, just readd the \b
in the negative lookahead
/(\w+\b)(?!.*\1\b)/
在 Rubular
这篇关于正则表达式 - 匹配所有单词但只匹配唯一单词一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!