-2

My question is what can be a valid regex for strings that don't contain a double letter. My solution is : b(ab)*a + a(ba)*b .

But i don't think it is correct, because it doesn't include the a or b. Can someone help me?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Alicia
  • 19
  • 7

1 Answers1

0

You can achieve this with a negative lookahead:

const re = /^(?!.*?(.).*?\1)[a-z]*$/g;

let s1 = "abcdefgh", s2 = "abcdefga";

console.log(re.test(s1));
console.log(re.test(s2));

How it works:

/^(?!.*?(.).*?\1)[a-z]*$/g
  • ^ asserts position at start of the string
  • Negative Lookahead (?!.*?(.).*?\1): Assert that the Regex below does not match
    • .*? matches any character (except for line terminators)
    • *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed
    • 1st Capturing Group (.)
    • . matches any character (except for line terminators)
    • .*? matches any character (except for line terminators)
    • *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed
  • \1 matches the same text as most recently matched by the 1st capturing group
  • Match a single character present in the list below [a-z]*
    • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    • a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
  • $ asserts position at the end of the string, or before the line terminator right at the end of the string (if any) Global pattern flags
  • g modifier: global. All matches (don't return after first match)

enter image description here

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44