views:

284

answers:

3

I am looking for a way to check if an exact string match exists in another string using Regex or any better method suggested. I understand that you tell regex to match a space or any other non-word character at the beginning or end of a string. However, I don't know exactly how to set it up.

Search String: t

String 1: Hello World, Nice to see you! t
String 2: Hello World, Nice to see you!
String 3: T Hello World, Nice to see you!

I would like to use the search string and compare it to String 1, String 2 and String 3 and only get a positive match from String 1 and String 3 but not from String 2.

Requirements:
Search String may be at any character position in the Subject.
There may or may not be a white-space character before or after it.
I do not want it to match if it is part of another string; such as part of a word.

For the sake of this question: I think I would do this using this pattern: /\bt\b/gi

/\b{$search_string}\b/gi

Does this look right? Can it be made better? Any situations where this pattern wouldn't work?
Additional info: this will be used in PHP 5

+2  A: 

Your suggestion of /\bt\b/gi will work and is probably the way to go. You've correctly used \b for word boundaries. You're using the global and case-insensitive modifiers which will find all matches in both cases. Simple, straight forward, clean. Look no further than what you've already come up with.

Asaph
yay! thank you :)
Jayrox
Ok, how would I set this up if the string starts with `#` such as `#t``/\b\#t\b/gi` isn't returning the results I expect.
Jayrox
@Jayrox: `#` is not a "word character" so it's impossible for `\b` to consider it to be a word boundary. Introducing the `#` transforms your question enough that I would consider it a new question. Please post a new question about matching `#t`.
Asaph
Ok, will do. Thanks again ;)
Jayrox
new question @ http://stackoverflow.com/questions/2827992/regex-to-check-if-exact-string-exists-including
Jayrox
+1  A: 

According to the old saying give a man a reg expression and he is happy for a day, teach him to write regular expression and he is happy for a lifetime (or something to that effect) try out the "regulator"

It provides a GUI and some pretty good examples for reg exp needs.

Anders K.
+2  A: 

Looks fine to me. You might want to check the exact meaning of the \b assertion to make sure it's exactly what you need.

Can't really name any situation where this pattern "wouldn't work" without a more elaborate description, but \b would work fine for your testcases.

Matti Virkkunen