问题
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