question

TZacks-2728 avatar image
0 Votes"
TZacks-2728 asked TZacks-2728 commented

C# Find using contains and replace exact match

Thanks for your example.

Here i am finding and replace. how to replace exact work. please suggest.

 xdcBrokerFiles = XDocument.Load(@f);
 popUpStandardLineItem = from item in xdcBrokerFiles.Descendants().Elements("TickerBrokerLineItemMap")
                         where item.Element("Formula").Value.Contains(olditem.Trim())
                             select item;
    
 foreach (var data in popUpStandardLineItem)
 {
     data.Element("Formula").Value.Replace(olditem.Trim(),newitem.Trim());
     xdcBrokerFiles.Save(@f);
 }

see this line data.Element("Formula").Value.Replace(olditem.Trim(),newitem.Trim()); where problem may occur during replace data in xml. so how to handle this kind of replace?

Thanks



dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

vb2ae avatar image
1 Vote"
vb2ae answered TZacks-2728 commented

You will need to change your code to something like this. String.Replace will replace any part of the string that matches the old value with the new value

  foreach (var data in popUpStandardLineItem)
  {
          if( data.Element("Formula").Value.Trim() == olditem.Trim())
          {
                    data.Element("Formula").Value = data.Element("Formula").Value.Replace(olditem.Trim(),newitem.Trim());
                  xdcBrokerFiles.Save(@f);
           }
  }
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I have done the job this way

 xdcBrokerFiles = XDocument.Load(@f);
 popUpStandardLineItem = from item in xdcBrokerFiles.Descendants().Elements("TickerBrokerLineItemMap")
                         where item.Element("Formula").Value.Contains(olditem.Trim())
                         select item;
    
 foreach (var data in popUpStandardLineItem)
 {
     data.Element("Formula").Value.ReplaceWholeWord(olditem.Trim(), newitem.Trim());
     xdcBrokerFiles.Save(@f);
 }


 public static string ReplaceWholeWord(this string original, string wordToFind, string replacement, RegexOptions regexOptions = RegexOptions.None)
         {
             string pattern = String.Format(@"\b{0}\b", wordToFind);
             string ret = Regex.Replace(original, pattern, replacement, regexOptions);
             return ret;
         }


am i on right direction to safe replace? thanks

0 Votes 0 ·

The code in the current foreach just got a string, you didn't set it to the new value of data.Element("Formula").Value.
Try this:

   data.Element("Formula").Value = data.Element("Formula").Value.ReplaceWholeWord(olditem.Trim(), newitem.Trim());
1 Vote 1 ·

Thank you sir pointing out this point.

0 Votes 0 ·