Click here to Skip to main content
15,850,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Im trying to develop this code that haves a string(ing) and a string array (splitwords).
I need to run a string and if it matches the string from the string array does something with that original string.

StringBuilder builder = new StringBuilder();

ing = " " + ing + " ";


foreach (string word in splitwords)

if (Regex.IsMatch(ing, @"(?<![\w])" + word + @"(?![\w])"))
// for example put the word in UPPERCASE


return builder.ToString();

With all the tests it runs ok, but if if I have

Text(ing): "I have a receipt with eggs but others with just one egg";

Words(splitwords): "egg","eggs", "have a receipt"

Result I get with the code above: "I HAVE A RECEIPT with EGG s but others with just one EGG"

What I need : "I HAVE A RECEIPT with EGGS but others with just one EGG"

How can I change my if condition to solve this problem?
CHill60 5-Jan-15 12:28pm    
You could try putting eggs in the list before egg, or use ing.ToLower() in your comparison
Member 10437316 5-Jan-15 12:31pm    
but eggs is before egg in the list. I order the list with the length of the word.

But if instead of using uppercase I want to do a different won t work.

1 solution

sample code:
var splitwords =new string[] {"egg","eggs", "have a receipt"}; 
string input ="I have a receipt with eggs but others with just one egg";
foreach (string word in splitwords)
	var regex = new Regex(@"(?<![\w])" + word + @"(?![\w])", RegexOptions.IgnoreCase);
	input = regex.Replace(input, m=>m.ToString().ToUpper());
//inpt = "I HAVE A RECEIPT with EGGS but others with just one EGG"

replace only the matching items of regex then it should work fine.
Share this answer
Member 10437316 5-Jan-15 12:56pm    
Excellent in this case for UpperCase words works . But just one more question if I need just to put an \a before the word and a \b at the end What should I do ?? Example string input ="I \ahave a receipt\b with \aeggs\b but others with just one \aegg\b";
DamithSL 5-Jan-15 13:03pm    
have you try like

input = regex.Replace(input, m=>@"\a" +m.ToString() +@"\b");
Member 10437316 5-Jan-15 13:10pm    
perfect ! Thanks a lot :)
DamithSL 5-Jan-15 13:12pm    
you are welcome!
BillWoodruff 5-Jan-15 16:52pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900