regular expressions

Viewed 50

Is it possible to merge these two regular expressions?

  • /^[A-Za-z]\S{3,30}$/
  • /^(?:(\w)(?!\1\1))+$/

I would like a string of:

  • only letters,
  • length between 3 and 30,
  • no spaces,
  • no to the repetition of the same letter more than two consecutive times (e.g: 'ddd' //false, 'dtdddyyt' //false, 'dtddyyt'//true).
2 Answers

You can use the second pattern as a negative lookahead assertion once to not match ddd in the string.

^(?!\S*(\w)\1\1)[A-Za-z]\S{3,30}$
  • ^ Start of string
  • (?! Negative lookahead
    • \S*(\w)\1\1 Match optional non whitespace chars, capture a word char and match the same with 2 backreferences
  • ) Close lookahead
  • [A-Za-z]\S{3,30} Match a single char A-Za-z and 3-30 non whitespace chars
  • $ End of string

Regex demo

const regex = /^(?!\S*(\w)\1\1)[A-Za-z]\S{3,30}$/;
[
  "ddad",
  "dtddyyt",
  "adaddd",
  "dtdddyyt",
  "ddd"
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));

You can use

/^(?:([A-Za-z])(?!\1{2})){3,30}$/
/^(?:(\p{Alphabetic})(?!\1{2})){3,30}$/u

See the regex demo. Note:

  • only letters - [A-Za-z] / \p{L} or \p{Alphabetic} (available in ECMAScript 2018+ compliant JS environments with /u flag)
  • length between 3 and 30 - {3,30}
  • no spaces - this condition is already covered by the first one
  • no to the repetition of the same letter more than two consecutive times - ([A-Za-z])(?!\1{2}).

JavaScript test:

const rx = /^(?:([A-Za-z])(?!\1{2})){3,30}$/;
const texts = ["ddad","dtddyyt","adaddd","dtdddyyt","ddd"];
for (let text of texts) {
  console.log(text, "=>", rx.test(text));
}

More details:

  • ^ - start of string
  • (?: - start of a non-capturing group (used as a container of a pattern sequence):
    • ([A-Za-z]) - Group 1: an ASCII letter (\p{L} / \p{Alphabetic} matches any Unicode letter)
    • (?!\1{2}) - right after the letter, there should not be two occurrences of the same letter
  • ) - end of the group
  • {3,30} - match three to thirty consecutive occurrences of the pattern sequence inside the non-capturing group
  • $ - end of string.
Related