Reputation: 73
I need a regular expression to match an exact word.
For example:
There is a string "draft guidance allerg Excellence"
and I want to search allerg
then I have written \ballerg\b
. It gives me exact match. But when I pass string as "draft guidance 12=allerg Excellence"
then it also return true, but this is wrong.
Which regular expression do I need to match only exact words?
Upvotes: 0
Views: 6185
Reputation: 38456
The \b
boundary would normally handle this situation, even in your case of "draft guidance 12=allerg Excellence"
; however, you're saying that the =
is part of the word (in normal English, this is not the case).
I'm assuming then that by "whole word", you mean a word that is surrounded by a space or normal sentence punctuation. In this case, a regex such as the following should work:
(?:^|[\s\.;\?\!,])allerg(?:$|[\s\.;\?\!,])
You can, obviously, add or remove characters as needed.
Regex Explained:
(?: # non-matching group
^ # beginning of string
| [\s\.;\?\!,] # OR a space, period, and other misc. punctuation
)
allerg # string to match
(?: # non-matching group
$ # end of string
| [\s\.;\?\!,] # OR a space, period, and other misc. punctuation
)
Upvotes: 6
Reputation: 6029
If i understood the question correctly, you want to match a word "allerg" . A word is enclosed with whitespace characters and "=allerg" has the "=" character which you dont want to match.
To match the word "allerg" you can use the following regex:
\s+allerg\s+
Upvotes: -1