whole word substring search w/o using regular expressions

S

seannakasone

Is there a way to search a string for a whole word w/o using a regular
expression?

i.e.
mystring.IndexOf(mypattern, *WholeWord);

The reason i rather not use a regular expression is because sometimes i
want to search for whole words w/o the regular expression special
characters being interpreted.
 
B

Bruce Wood

Why not simply escape the relevant characters in the word and then
build it into a regular expression? You could then wrap it all in a
method call:

int wordIndex = WordIndex(myString, wordString);
 
J

Jon Skeet [C# MVP]

Is there a way to search a string for a whole word w/o using a regular
expression?

i.e.
mystring.IndexOf(mypattern, *WholeWord);

Do you know what word separators will be involved? In other words, will
there always be spaces between words?
The reason i rather not use a regular expression is because sometimes i
want to search for whole words w/o the regular expression special
characters being interpreted.

You can use Regex.Escape to escape all the special characters, then use
the normal word boundary character classes etc. That sounds like the
best bet here, unless the word delimiter will always be the exact same
thing.
 
S

seannakasone

spaces will be the word separators. thanks i guys, i'll look into the
escape method.
 
J

Jon Skeet [C# MVP]

spaces will be the word separators.

In that case, you could just use foo.IndexOf (" "+word+" ")

You could use foo.StartsWith (word+" "),
foo.EndsWith(" "+word) and
foo.Equals(word)

to check for edge cases.
 

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

Top