Regular Expression For Duplicate Words

后端 未结 13 2031
终归单人心
终归单人心 2020-11-22 11:13

I\'m a regular expression newbie, and I can\'t quite figure out how to write a single regular expression that would "match" any duplicate consecutive words such as

13条回答
  •  旧巷少年郎
    2020-11-22 12:08

    Regex to Strip 2+ duplicate words (consecutive/non-consecutive words)

    Try this regex that can catch 2 or more duplicates words and only leave behind one single word. And the duplicate words need not even be consecutive.

    /\b(\w+)\b(?=.*?\b\1\b)/ig
    

    Here, \b is used for Word Boundary, ?= is used for positive lookahead, and \1 is used for back-referencing.

    Example Source

提交回复
热议问题