C# 正则表达式仅在标签外替换字符串 [英] C# Regex replace in string only outside tags

查看:36
本文介绍了C# 正则表达式仅在标签外替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它代表了 xml 的一部分.

I have a string, which represents part of xml.

string text ="word foo<tag foo='a' />another word "

并且我需要替换此字符串中的特定单词.所以我使用了这个代码:

and I need to replace particular words in this string. So I used this code:

Regex regex = new Regex("\\b" + co + "\\b", RegexOptions.IgnoreCase);
return regex.Replace(text, new MatchEvaluator(subZvyrazniStr));
static string     subZvyrazniStr(Match m)
    {
        return "<FtxFraze>" + m.ToString() + "</FtxFraze>";
    }

但我的代码的问题是,它也替换了标签内的字符串,这是我不想要的.那么我应该添加什么来替换标签外的单词?

But the problem of my code is, that it also replaces string inside tags, which i don't want to. So what should I add, to replace words only outside tags?

例如:当我将变量 co 设置为 "foo" 时,我想返回 "word <FtxFraze>foo</FtxFraze><tag foo='a'/>another word"

Ex.: when I set variable co to "foo" I want to return "word <FtxFraze>foo</FtxFraze><tag foo='a' />another word"

谢谢

推荐答案

如果您不那么挑剔,像这样的简单技巧在某些情况下就足够了:

A simple trick like this may suffice in some cases if you are not that picky:

\bfoo\b(?![^<>]*>)

这篇关于C# 正则表达式仅在标签外替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆