admin管理员组

文章数量:1391804

/([a-zA-Z]).*?\1/

This regular expression currently returns true on .test() if it finds 1 matching repeating letter. I want it to match atleast 3 or 2 for that matter and return true.

For example, currently it returns true on .test() for strings like;

Trickster, Been, Dekko

But I want it to return true only if there are more than 2 matches so that the following would return true on .test()

CordCord, XoXo, XolXol, PiunPiun

And NOT return true on the strings I mentioned earlier.

/([a-zA-Z]).*?\1/

This regular expression currently returns true on .test() if it finds 1 matching repeating letter. I want it to match atleast 3 or 2 for that matter and return true.

For example, currently it returns true on .test() for strings like;

Trickster, Been, Dekko

But I want it to return true only if there are more than 2 matches so that the following would return true on .test()

CordCord, XoXo, XolXol, PiunPiun

And NOT return true on the strings I mentioned earlier.

Share Improve this question edited Jun 25, 2017 at 12:52 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked May 17, 2017 at 18:05 DyukalouDyukalou 652 silver badges10 bronze badges 1
  • Please check my answer. And no, the question is not bad. – Wiktor Stribiżew Commented May 17, 2017 at 18:21
Add a ment  | 

2 Answers 2

Reset to default 5

You may use a limiting quantifier {2,} after [a-zA-Z] to match 2 or more occurrences of the pattern:

([a-zA-Z]{2,}).*?\1

See the regex demo

Details

  • ([a-zA-Z]{2,}) - Capturing group 1 matching 2 or more ASCII letters
  • .*? - any 0+ chars other than line breaks, as few as possible (lazy)
  • \1 - backreference matching the same text as captured in Group 1.

Note that the 2 or more ASCII letters should be captured into 1 group (hence the limiting quantifier is inside the capturing parentheses).

var ss = ['Trickster, Been, Dekko', 'CordCord, XoXo, XolXol, PiunPiun'];
var re = /([a-zA-Z]{2,}).*?\1/;
for (var s of ss) {
  console.log(s,"=>",re.test(s));
}

You could specify at least three like this: /([a-zA-Z]){3,}.*?\1/

> /([a-zA-Z]){3,}.*?\1/.test('Been')
<- false
> /([a-zA-Z]){3,}.*?\1/.test('CordCord')
<- true

本文标签: javascriptJS Regexp for letter that appears at least twice anywhere in the stringStack Overflow