views:

118

answers:

4

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

+1  A: 

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

Martin Milan
But maybe you need the '*' quantifier instead of the '?' to account for multiple spaces.
Hans Kesting
@Hans - Possibly - it's not clear from the question...
Martin Milan
@Martin - that's why I said "maybe", but I should have mentioned that explicitly.
Hans Kesting
A: 

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.

biozinc
+1. But why can't you use this method instead newString = originalString.Replace(" ", "");
Veer
+3  A: 

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
Konstantin Spirin
I have deleted my response in support of this which was basically the same answer. no point in duplicate answers.
krystan honour
A: 

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
Kyra