匹配但忽略b的子串的模式

时间:2012-08-10 19:41:32

标签: c# regex pattern-matching

  

可能重复:
  Find a pattern to match ‘a’, ignoring that ‘a’ which lies within ‘b’ and ‘c’

如果我有以下字符串(例如)

string q = "select field1 from t1 where field1 in (select field1 from t2)";

在这种情况下,我有

a = " from"; b = @"\(.* from.*\)"; => " from" within parenthesis

您可以在此处看到'a'是'b'的子字符串

我最接近的模式是

string pat = @"^((?!\(.* from.*\)).)* from((?!\(.* from.*\)).)*$";

但我需要'pat'修改'a' such that 'a' is not a sub-string of 'b' ...('a'和'b'是可变模式)。我坚持用正则表达式翻译它。我想用

string answer=Regex.Relace(q , pat , ",field2 from");

期望的输出:(答案中的值应该是)

"select field1,field2 from t1 where field1 in (select field1 from t2)"

3 个答案:

答案 0 :(得分:2)

为什么不在匹配模式中包含t1?

string pattern = " from t1";
string answer=Regex.Relace(q , pattern , ",field3 from t1");

答案 1 :(得分:1)

你试图限制替换次数,听起来似乎已经在这里回答了这个问题:

How to Regex search/replace only first occurrance in a string in .NET?

[编辑:]回复第一条评论:

抱歉,不知道FROM是一个例子还是你实际上想要做的事情。试图替换不基于可控字符串的某些符号是有问题的。如果你不控制进入的所有字符串,你可能还需要处理类似这样的情况:

SELECT [From], [To], [Email], [Subject] FROM EmailsSent

最终结果是你的正则表达式必须向前和向后检查括号和括号,因为你没有100%控制它给出的字符串。我要提醒你,你所做的事情听起来像是一种不好的做法,只有在没有其他选择的情况下才能做到。看一下前瞻/后方信息,您应该可以更多地了解它:

http://openmymind.net/2011/2/16/Regex-Positive-Negative-Look-Ahead-Behind/

答案 2 :(得分:0)

string q = "select field1,field2 from t1 where field1 in (select field1 from t2 where t2.field2>5)";

Regex r=new Regex(@"from.*$");
string s=r.Replace(q,",field3 $0");//output
相关问题