常规的前pression环视 [英] regular expression lookaround
问题描述
我不认为这是可能的只是普通的EX pressions,但我不是专家,所以我认为这是值得一问。
我试图做一个大规模的搜索和替换的C#code,使用.NET正则表达式。我想要做的就是找到一行code其中一个特定函数被调用的一个变量,它是DateTime类型。例如:
axRecord.set_Field(CreatedDate,m_createdDate);
和我想知道这是一个DateTime变量B / C早些时候在code文件将是该行:
日期时间m_createdDate;
但似乎我不能使用一个名为group负后向这样的:
(小于?=日期时间\ K< 1>?+)axRecord.set _ [^] +(LT; 1> [^)] +)
如果我尝试匹配的变量声明和这样的函数调用之间的所有文本:
日期时间(小于?1> [^;] +)+ axRecord.set + \ K<。?。?1>
它会找到第一场比赛 - 第一款基于第一个变量声明 - 但它无法找到任何其他比赛中,因为code的布局是这样的:
日期时间m_First;
日期时间m_Second;
...
axRecord.set_Field(东西,m_First);
axRecord.set_Field(somethingElse,m_Second);
和第一场比赛包括第二个变量声明。
有没有一种好方法,只需定期EX pressions做到这一点,还是我不得不求助于脚本在我的逻辑?
试试这个:
<$p$p><$c$c>@"(?s)set_Field\(""[^""]*"",\s*(?<vname>\w+)(?<=\bDateTime\s+\k<vname>\b.+)"
通过先进行回顾后,你迫使正则表达式来搜索特定顺序的方法调用:在该变量声明的顺序。你想要做的是首先匹配一个可能的前瞻性的方法调用,然后使用后向验证变量的类型。
我只是做了一个粗略的猜测相匹配的方法调用的部分。像其他人所说,不管你用的是将不得不进行调整以适应您的code正则表达式;有没有通用的解决方案。
I don't think this is possible with just regular expressions, but I'm not an expert so i thought it was worth asking.
I'm trying to do a massive search and replace of C# code, using .NET regex. What I want to do is find a line of code where a specific function is called on a variable that is of type DateTime. e.g:
axRecord.set_Field("CreatedDate", m_createdDate);
and I would know that it's a DateTime variable b/c earlier in that code file would be the line:
DateTime m_createdDate;
but it seems that I can't use a named group in negative lookbehind like:
(?<=DateTime \k<1>.+?)axRecord.set_[^ ]+ (?<1>[^ )]+)
and if I try to match the all the text between the variable declaration and the function call like this:
DateTime (?<1>[^;]+).+?axRecord.set.+?\k<1>
it will find the first match - first based on first variable declared - but then it can't find any other matches, because the code is laid out like this:
DateTime m_First;
DateTime m_Second;
...
axRecord.set_Field("something", m_First);
axRecord.set_Field("somethingElse", m_Second);
and the first match encompasses the second variable declaration.
Is there a good way to do this with just regular expressions, or do I have to resort to scripting in my logic?
Try this:
@"(?s)set_Field\(""[^""]*"",\s*(?<vname>\w+)(?<=\bDateTime\s+\k<vname>\b.+)"
By doing the lookbehind first, you're forcing the regex to search for the method calls in a particular order: the order in which the variables are declared. What you want to do is match a likely-looking method call first, then use the lookbehind to verify the type of the variable.
I just made a rough guess at the part that matches the method call. Like the others have said, whatever regex you use is going to have to be tailored to your code; there's no general solution.
这篇关于常规的前pression环视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!