tags:

views:

550

answers:

7

Can someone supply me with the regexp for searching for a searchterm 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 searchresults but key. is okay.

Thanks!

+1  A: 

If using Perl what you need is \b aka "word boundary" ...

m/\bkey\b/

siukurnin
I'm gonna use it in a mysql query.
Overbeeke
+6  A: 

\bkey\b should do what you want.

\b is a word boundary

Greg
/learns something new
Andrew Bullock
Will this find "_word_" or "word4"? Are underscores and numbers word boundaries? +1 or Pax Diablo's answer, which answer the question exactly as asked.
Adam Liss
+2  A: 

Does \b work?

Will key! or key. be found? And what about $key$?

+7  A: 

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$".

paxdiablo
This is the solution that works within a mysql query: WHERE column REGEXP '[^A-Za-z]key[^A-Za-z]' , the word boundary \b does not work in mysql. Thanks!
Overbeeke
Much appreciated - I didn't realize from your question that you were referring to mysql. Now all you need to do is accept the answer :-) .
paxdiablo
One question though. A character is now expected before key. If the value of my column starts with key then the regex does not find it. How can i make it optional?
Overbeeke
According to the MySQL doc Anders linked to, word boundaries are matched with `[[:<:]]` (start of word) and `[[:>:]]` (end of word).
Alan Moore
@Overbeeke: you may need to do WHERE column REGEXP 'regex1' OR column REGEXP 'regex2' OR column REGEXP 'regex3', using the three regexes I gave - the second matches your key at the start, the third matches at the end.
paxdiablo
+1  A: 

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

Note that, by requiring a non-word character before and after "key", this will not match "key" at the beginning or end of the line. (The absence of a character is not a non-word character.)
Dave Sherohman
+3  A: 

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

Anders Waldenborg
A: 

No need for the "OR"s like this:

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

davew