Regex: match whole word

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?
 
M

Martin Z

[\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?
 
B

Ben Voigt

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.
 
G

Greg Bacon

: 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
 
G

Greg Bacon

: 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Replace email 1
Regex 3
Are you a RegEx bandido? 2
Obfuscate Email 1
Obfuscate 4
Problem Creating Regex Expression 5
Regex: Capturing HTML 1
Regex help 2

Top