忽略模式时用正则表达式替换字符串 [英] string replace with regex while ignoring a pattern

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

问题描述

您好,我想创建一个正则表达式,以便能够用另一个字符串替换一个字符串,同时还要确保避免替换特定的模式.

例如:string是-我想买房子,这房子真好,我会{买|买|租|获得}这个地方

该应用程序应将购买替换为购买,但不要放在方括号中.我的意思是所有发生的购买都应替换为购买,但忽略属于{}的购买.

我为方括号构建的正则表达式是这样的:

Dim regex As New Regex("{([^{}]+)}")



但请帮助我创建一个正则表达式,在这里我可以替换字符串,也可以排除上述模式.

这两个单独的表达式就像:

rgx = New Regex("buy", RegexOptions.IgnoreCase)


Dim regex As New Regex("{([^{}]+)}")



解决方案

(?!{[^{]*)buy(?![^{}]*})
这就是你想要的.此正则表达式将为您提供{}中未包含的购买字词.

您可以匹配多个单词,例如(?!{[^{]*)buy|purchase(?![^{}]*})
你可以这样

  Dim  rgx  As   Regex(" )
 Dim 结果 As   String  = rgx.Replace (输入,替换)' 其中输入将是您的内容,替换将是要放置的单词 


解决方案是下面的方法System.Text.RegularExpression命名空间,

 Regex.Replace 



有关更多详细信息,请访问: http://msdn.microsoft.com/en-us/library/h0y2x3xs.aspx [^ ]


Hello, i want to create a regex to be able to replace a string with another string while also making sure that a particular pattern is avoided from being replaced.

Eg : string is - I wanted to buy a house and this house is so good that i will {buy|purchase|rent|acquire} this place

The application should replace buy with purchase but not in the brackets. I mean all the occurences of buy should be replaced with purchase but ignore the ones that fall under {}.

The regex that i build for the brackets is this :

Dim regex As New Regex("{([^{}]+)}")



but please help me to create a regex where i can replace string and also exclude the above pattern.

the two individual expression would be like :

rgx = New Regex("buy", RegexOptions.IgnoreCase)


Dim regex As New Regex("{([^{}]+)}")



how do i merge the two to include first and exclude second one?

解决方案

(?!{[^{]*)buy(?![^{}]*})
This is what you want. This regex will get you the buy word not enclosed in {}.

You can match multiple words like (?!{[^{]*)buy|purchase(?![^{}]*})
You can do it like

Dim rgx As New Regex("(?!{[^{]*)buy|purchase(?![^{}]*})")
Dim result As String = rgx.Replace(input, replacement) 'where input will be your content and replacement will be the word to be placed


Solution for your problem is the below method System.Text.RegularExpression namespace,

Regex.Replace



More details at: http://msdn.microsoft.com/en-us/library/h0y2x3xs.aspx[^]


这篇关于忽略模式时用正则表达式替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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