91DarioDev
91DarioDev

Reputation: 1690

Regular expression that matches only if there is exactly one occurrence

I wrote this regex

(<b>)\b[a-zA-Z][a-zA-Z0-9_]{4,15}</b>

But I would like that the match is triggered only if there is exactly one occurrence, so I thought I need to do this

((<b>)\b[a-zA-Z][a-zA-Z0-9_]{4,15}</b>){1}

But it doesn't seem to work. What I am doing wrong?

Upvotes: 1

Views: 874

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

Try using a negative lookahead to assert that a second match does not occur:

^(?!.*\b[a-zA-Z][a-zA-Z0-9_]{4,15}\b.*\b[a-zA-Z][a-zA-Z0-9_]{4,15}\b).*\b[a-zA-Z][a-zA-Z0-9_]{4,15}\b.*$

This is a verbose regex, and very hard to read. Let's say you wanted to match strings in which the word BAT occurred once and only once. We could write:

^(?!.*\bBAT\b.*\bBAT\b).*\bBAT\b.*$

Upvotes: 2

Related Questions