开发者

C# - How do find a string within a string even if it spans across whitespace?

I want to be able to find and highlight a string within a string BUT I no not want to remove the space.

So if my original string is :

There are 12 monkeys

I want to find '12 mon' and highlight those characters开发者_如何学C ending up with :

There are < font color='red' >12 mon< /font >keys

BUT I also want the same result if I search for '12mon' (no space this time)

This has really bent my mind! I'm sure it can be done with Regex.


Use * to specify that spaces are optional and use Replace method of Regex class:

var input = "There are 12 monkeys";

var result = Regex.Replace(input, @"12\s*mon", @"<font color='red'>$0</font>");

And the result is:

There are <font color='red'>12 mon</font>keys


You could regex for 1\s?2\s?m\s?o\s?n\s?

You'd need to write a function to generate the regex, but it shouldn't be too hard. Notice I didn't use include the actual space when I created the regex...


It's fast enough, this is a lot neater: just search both the original string and this one:

originalString.ToCharArray().Where(c => !Char.IsWhiteSpace(c));

I imagine most processing time will be spent re-building your HTML string anyways, so the cost of parsing to char array shouldn't be a major issue.


Konstantin's answer doesn't account for if the space is somewhere else. So instead I would take the input the user wants to search for and insert "\w*' in every position and that way any possible search can be found.

var searchTerm = "eare1";
var input = "There are 12 monkeys";
var result = Regex.Replace(input, @"e\s*a\s*r\s*e\s*1", @"<font color='red'>$0</font>");

And the result is:

Ther<font color='red'>e are 1</font>2 monkeys
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜