penk
penk

Reputation: 259

Regex match whole words with special characters

I have a string (csv) like this:

american, american , latin-american, American, AMERICAN

I have tried this \bamerican\b but it matches all five words. It seems like it ignores some special characters like "-" and " ". It is also case-insensitive.

What it is supposed to do is ignore only the ",". It also has to be case-sensitive.

So the only match word was "american" (the first word on that string).

How can I achieve this?

Upvotes: 0

Views: 105

Answers (1)

SaSkY
SaSkY

Reputation: 1086

Try this:

(?:^|(?<=,\s))american(?:(?=,)|$)

See regex demo

import re
txt = 'american, american , latin-american, American, AMERICAN'
re.findall('(?:^|(?<=,\s))american(?:(?=,)|$)', txt)

//Output: ['american'] the first one.

Upvotes: 2

Related Questions