Linked Questions

Popular Questions

Regex match any word that contains a sequence exactly once

Asked by At

I need a regular expression that matches any word containing, let's say, the sequence 'ab' exactly once. So it should match these:

  • aaaabaaa
  • ab
  • abomination

and not these:

  • something
  • abab
  • bacba

With my current regex \w*ab\w* I get all of the first list but also the second one of the second list as you can see in the snippet below. How can I specify that it should only match if it contains exactly one 'ab'?

let text = "aaaabaaa ab abomination something abab bacba",

console.log(text.match(/\w*ab\w*/ig));

I searched for a while and didn't find a solution but if this is a duplicate of some kind please let me know and I will remove the question.

Related Questions