sjh
sjh

Reputation: 3

matching a word only if it is unique

I've spent the day trying to use regex to match a word only where the word is unique. It's not working and I can't figure out what I'm doing wrong.

I need something that will match only a unique instance of "ST", such as:

but fail with these:

I thought this lookahead would work, but no such luck:

(\bST\b)(?!(\bST\b))

What am I missing?

Upvotes: 0

Views: 60

Answers (2)

spaark
spaark

Reputation: 711

You can use following pattern:

^(?!(.*\bST\b){2,}).*\bST\b

This does a negative lookahead right away in which it checks if there are 2 or more occurrences of \bST\b. If there aren't, it moves on in the pattern and checks if there is at least one.

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can use RegExp /\bST\b/g and .match(), check .length of matched string

const matches = (str, re = /\bST\b/g, match = str.match(re)) => 
                  !!match && match.length === 1;

const arr = [
"1 MARY ST WASHINGTON"
, "1 ST MARY ST WASHINGTON"
, "1 ST MARY ST MT ST HELENS"
, "1 MARY RD WEST WASHINGTON"
, "1 MARY RD WASHINGTON"
];

console.log(arr.map(s => matches(s)));

Upvotes: 1

Related Questions