Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

.net - Regex expression to match whole word ?

In reference to my question Regex expression to match whole word with special characters not working ?,

I got an answer which said

@"(?<=^|s)" + pattern + @"(?=s|$)"

This works fine for all cases except 1 case. It fails when there is space in the pattern.

Assume string is "Hi this is stackoverflow" and pattern is "this " , then it says no matches. This happens because of an empty space after the actual string in pattern.

How can we handle this ? Ideally speaking it should say one match found !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

(?:(?<=^|s)(?=S)|(?<=S|^)(?=s))this (?:(?<=S)(?=s|$)|(?<=s)(?=S|$))

See it here on Regexr

This will also work for pattern that starts with a whitespace.

Basically, what I am doing is to define a custom "word" boundary. But it is not true on a W=>w or a w=>W change, its true on a S=>s or a s=>S change!

Here is an example in c#:

string str = "Hi this is stackoverflow";
string pattern = Regex.Escape("this");
MatchCollection result = Regex.Matches(str, @"(?:(?<=^|s)(?=S)|(?<=S|^)(?=s))" + pattern + @"(?:(?<=S)(?=s|$)|(?<=s)(?=S|$))", RegexOptions.IgnoreCase);

Console.WriteLine("Amount of matches: " + result.Count);
foreach (Match m in result)
{
    Console.WriteLine("Matched: " + result[0]);
}
Console.ReadLine();

Update:

This "Whitespace" boundary can be done more general, so that on each side of the pattern is the same expression, like this

(?:(?<=^|s)(?=S|$)|(?<=^|S)(?=s|$))

In c#:

MatchCollection result = Regex.Matches(str, @"(?:(?<=^|s)(?=S|$)|(?<=^|S)(?=s|$))" + pattern + @"(?:(?<=^|s)(?=S|$)|(?<=^|S)(?=s|$))", RegexOptions.IgnoreCase);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...