Regex: match whole word

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

is there a simple way to make it so your regex only matches whole words?

i was thinking simply something like:

[^a-zA-Z0-9]*match_string[^a-zA-Z0-9]*

but then I think it would fail if the word was at the beginning or end of a
line?
 
[\w]+ better - match any alphanumeric character group of length 1 or
more (* is zero or more).
well...wouldn't

[\w]*

work?
is there a simple way to make it so your regex only matches whole words?

i was thinking simply something like:

[^a-zA-Z0-9]*match_string[^a-zA-Z0-9]*

but then I think it would fail if the word was at the beginning or end of a
line?
 
MrNobody said:
is there a simple way to make it so your regex only matches whole words?

i was thinking simply something like:

[^a-zA-Z0-9]*match_string[^a-zA-Z0-9]*

but then I think it would fail if the word was at the beginning or end of
a
line?

You want to use the "negative look-ahead" (and behind) construct.
 
: ibiza wrote:
:
: > well...wouldn't
: >
: > [\w]*
: >
: > work?
:
: [\w]+ better - match any alphanumeric character group of length 1 or
: more (* is zero or more).

The brackets are redundant: \w+ does the job.

Greg
 
: is there a simple way to make it so your regex only matches whole
: words?
:
: i was thinking simply something like:
:
: [^a-zA-Z0-9]*match_string[^a-zA-Z0-9]*
:
: but then I think it would fail if the word was at the beginning or end
: of a line?

What's your idea of whole words?

You can use \b to match word boundaries, e.g., @"\bwhole words\b".

If I'm not on the right track, please illustrate with examples.

Greg
 
Back
Top