Overbeeke
Overbeeke

Reputation: 2028

Regular expression for search terms not preceded or followed by [a-z] and [A-Z]

Can someone supply me with a regex to match a search term that is not preceded or followed by [a-z] and [A-Z]? (Other characters are OK.) I.e., when searching for key, I don't want keyboard in my search results, but key. is okay.

Upvotes: 3

Views: 2323

Answers (6)

davew
davew

Reputation: 1

No need for the ORs if you do it like this:

(^|[^A-Za-z])key([^A-Za-z]|$)

Upvotes: 0

Anders Waldenborg
Anders Waldenborg

Reputation: 3035

As this question is tagged with I assume you are using MySQL regexps. Then [[:<:]]key[[:>:]] is what you want. See the documentation at dev.mysql.com for details.

Upvotes: 3

siukurnin
siukurnin

Reputation: 2902

If you're using Perl, what you need is \b, aka "word boundary":

m/\bkey\b/

Upvotes: 1

Alex
Alex

Reputation:

Or the more concise [^\w]key[^\w]

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 882028

Since you don't specify what regex engine you're using, I'll assume a baseline, in which case "[^A-Za-z]key[^A-Za-z]" would be sufficient.

If you also want to catch the string at the start and end of the line, you'll also have to use "^key[^A-Aa-z]" and "[^A-Aa-z]key$".

Upvotes: 7

Greg
Greg

Reputation: 321766

\bkey\b should do what you want.

\b is a word boundary

Upvotes: 6

Related Questions