Remove / g at the end of regExPattern. This is the first mistake that I see for sure. The .NET regex implementation does not have a global modifier, by default it is global.
UPDATE:
I think this should work:
//define the string string xmlString = "<xml><elementName specificattribute=\" 111 222 333333 \" anotherattribute=\"something\" somethingelse=\"winkle\"><someotherelement>value of some kind</someotherelement><yetanotherelement>another value of some kind</yetanotherelement></elementName></xml>"; // here the regExPattern - the syntax checker doesn't like this at all string regExPattern = "(specificattribute=)\"\\s*([^\"]+?)\\s*"; // here the replacement string replacement = "$1\"$2\""; Regex rgx = new Regex(regExPattern); string result = rgx.Replace(xmlString, replacement);
Although this may work for you, the XML-nested / context-sensitive nature makes regular expressions unsuitable for proper and efficient parsing. This, of course, is not the best tool for the job, so to speak.
From the look of things, you should really use something like Xpath or Linq to XML to parse and modify these attributes.
I practically steal Mark Bayer's answer, but since his example is with xml files, and you do it in memory, it should be something like this:
XDocument doc = XDocument.Parse("<xml><elementName specificattribute=\" 111 222 333333 \" anotherattribute=\"something\" somethingelse=\"winkle\"><someotherelement>value of some kind</someotherelement><yetanotherelement>another value of some kind</yetanotherelement></elementName></xml>"); foreach (XAttribute attr in doc.Descendants("elementName") .Attributes("specificattribute")) { attr.Value = attr.Value.Trim(); } string result = doc.ToString();
source share