Regular Exp find duplicate phrases 2 sequentially words in a pattern

一曲冷凌霜 提交于 2019-12-13 10:14:01

问题


I would like to catch 2 words sequentially duplicated in a pattern

I would like to be able to catch duplicate words in this case "cancer cervical" because they are the only duplicate 2 words sequentially.

pattern "cancer cervical diane mortality cervical cancer cervical diane sea"

I use this Regular expression but still can't catch 2 sequentially duplicated words.

/(\W|^)(.+)\s\2/ig

回答1:


This should be able to do the job: /(\w+\s\w.*)\s.*\1/ if you are dealing with words including numbers.

var string = "cancer cervical diane mortality cervical cancer cervical diane sea";
var regex = /(\w+\s\w.*)\s.*\1/;
console.log(string.match(regex));

var string = "cancer cervical diane mortality cervical cancer cervical diane sea";
var string1=" this is a test cancer cervical cancer diane mortality cervical cancer cervical diane sea";
var string2=" test whether it will catch one word cancer mortality cervical cancer cervical diane sea";
var regex = /(\w+\s\w.*)\s.*\1/;
console.log(string.match(regex));
console.log(string1.match(regex));
console.log(string2.match(regex));



回答2:


It sounds like you're simply looking for /(.+)\s\1/.

This will match any character(s) that are separated by a space.

In your example, it will match the cer of both cancer and cervical:

var string = "cancer cervical diane mortality cervical cancer cervical diane sea";
var regex = /(.+)\s\1/;
console.log(string.match(regex));

This can also be seen working on Regex101 here.



来源:https://stackoverflow.com/questions/50166537/regular-exp-find-duplicate-phrases-2-sequentially-words-in-a-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!