简体   繁体   English

我想使用正则表达式替换文本

[英]I want to replace text using Regex

In my code i am trying to replace <Run Foreground="#FFFF0000"> with <Run Foreground="#FFFF0000" Text=" 在我的代码中,我尝试将<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=" 它将<Run Foreground="#FFFF0000">替换为<Run Text="

I just want to replace > with text = " whenever i encounter <Run . 我只想在遇到<Run时用文本=>替换>。

How can i archive this ? 我该如何存档?

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). 现在,这将仅匹配> ,并在任意数量的非<字符之后(在同一标记内)后跟<Run

If this is an XML document, then you can just use XPath to select the Run elements and add attributes to the selected elements. 如果这是XML文档,则可以仅使用XPath选择Run元素并将属性添加到所选元素。 It's a better option than using Regex. 比使用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. 注意:我还没有测试过,但是应该可以给您一个好主意。

Option 1) 选项1)

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

Option 2) 选项2)

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

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM