2

In my code i am trying to replace <Run Foreground="#FFFF0000"> with <Run Foreground="#FFFF0000" Text="

right now i am using this

Regex.Replace(XMLString, @"<Run.*?>", "<Run Text=\"", RegexOptions.IgnoreCase); 

which replaces <Run Foreground="#FFFF0000"> with <Run Text="

I just want to replace > with text = " whenever i encounter <Run .

How can i archive this ?

madhu.13sm
  • 344
  • 1
  • 2
  • 13

4 Answers4

2

An alternative to capturing would be to use a lookbehind:

Regex.Replace(XMLString, @"(?<=<Run[^<]*)>", " Text=\"", RegexOptions.IgnoreCase);

This will now only match > that are preceded by <Run after an arbitrary number of non-< character (so within the same tag).

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
2

If this is an XML document, then you can just use XPath to select the Run elements and add attributes to the selected elements. It's a better option than using Regex.

Try something like this:

string txtAttributeName = "Text";
foreach(XmlNode element in xmlDocument.SelectNodes(".//Run")
{
    if (element.Attributes.GetNamedItem(txtAttributeName) == null)
    {
        XmlAttribute txtAttribute = xmlDocument.CreateAttribute(txtAttributeName);
        txtAttribute.Value = "Whatever you want to place here";

        element.Attributes.Append(txtAttribute);
    }
}

Note: I haven't tested this, but it should give you a good idea.

Kiril
  • 39,672
  • 31
  • 167
  • 226
1

Option 1)

Regex.Replace(XMLString, @"(<Run.*?)>", "$1 Text=\"", RegexOptions.IgnoreCase);

Option 2)

Regex.Replace(XMLString, @"(?<=<Run.*?)>", " Text=\"", RegexOptions.IgnoreCase);
Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • Note that, while equivalent, my version of option two is slightly more efficient (and generally recommended practice), because it avoids backtracking. (In fact, the same would apply to option 1) – Martin Ender Oct 19 '12 at 21:15
  • A minor issue here: I haven't tested it, but I suspect that this won't work when this is a self-closing tag (i.e. ``). It should be easy to fix that tho. – Kiril Oct 19 '12 at 21:19
  • @Lirik, I suppose the OP is quite sure that the tag will contain something and will not be self-closing. – Martin Ender Oct 19 '12 at 21:20
  • @m.buettner - Friend, find an error in your solution before I will downvote you... – Ωmega Oct 19 '12 at 21:23
  • @Ωmega the OP is just adding an attribute to an XML element. – Kiril Oct 19 '12 at 21:23
  • @Lirik, how can you consider it as adding an attribure, when he is removing `>` from tag? There is a syntax issue for me! – Ωmega Oct 19 '12 at 21:36
0

You need to capture the text you want to keep, then re-add it. I haven't test this, but:

Regex.Replace(XMLString, @"<Run(.*?)>", "<Run$1 Text=\"", RegexOptions.IgnoreCase); 
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122