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.

C#
StringBuilder builder = new StringBuilder();

ing = " " + ing + " ";

builder.Append(@"{\rtf1\ansi");

foreach (string word in splitwords)
{

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

builder.Append(ing);
builder.Append(@"}");


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?
Posted
Comments
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 thing..it won t work.

1 solution

sample code:
C#
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
 
v3
Comments
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    
+5

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