正则表达式忽略.NET带引号的字符串中的文本 [英] RegEx ignore text inside quoted strings in .net

查看:100
本文介绍了正则表达式忽略.NET带引号的字符串中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何忽略.NET引用字符串中的文本。 我有以下字符串

这是考验,这是测试内部报价

说我搜索测试和更换它应该只替换测试不是$ P $内psent报价。

这是,这是内部测试报价。

我米以此来匹配带引号的文本中的文本。

(['])。*?\ 1

解决方案

我会使用 Regex.Replace()。正则表达式将匹配一个不带引号的字符串,后跟带引号的字符串和匹配评估将取代测试在不带引号的一部分。事情是这样的:

  Regex.Replace(这是考验,这是测试内部报价测试,
              @(。*?)((小于报价>?['])* \ K<报价> |。?$),
              M => m.Groups [1] .Value.Replace(测试,)+ m.Groups [2]。价值)
 

组1是所述非引述部分,第2组是引部分(或字符串的末尾)。以上的结果是:

这是,这是测试内部报价

How to ignore text inside a quoted string in .NET. I have following string

This is test, 'this is test inside quote'

Say I'm searching for test and replacing it should only replace test not present inside the quote.

This is, 'this is test inside quote'. 

I m using this to match text inside the quoted text.

(["']).*?\1

解决方案

I would use Regex.Replace(). The regex would match a non-quoted string followed by a quoted string and the match evaluator would replace test in the non-quoted part. Something like this:

Regex.Replace("This is test, 'this is test inside quote' test",
              @"(.*?)((?<quote>[""']).*?\k<quote>|$)",
              m => m.Groups[1].Value.Replace("test", "") + m.Groups[2].Value)

Group 1 is the non-quoted part, group 2 is the quoted part (or the end of the string). The result of the above is:

This is , 'this is test inside quote' 

这篇关于正则表达式忽略.NET带引号的字符串中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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