regex - 替换为条件 DTE

标签 regex vb.net if-statement envdte replacewith

我想匹配术语“TextCtrls”和“LabelCtrls”。 当我找到“TextCtrls”时,我想替换为“Txt”,当我找到“LabelControls”时,我想替换为“Lbl”。 Online Demo

这可以通过 DTE.Find.ReplaceWith 实现吗?

DTE.Find.FindWhat = "Container\(""\w+""\)\.(?:TextCtrls|LabelCtrls)\(""(?<ControlName>\w+)""\).Text"

DTE.Find.ReplaceWith = "<psydocode:Txt|Lbl>${ControlName}.Text"

最佳答案

解决方案 1:重用输入字符串中存在的文本

由于您要替换的文本实际上存在于源文本中,因此您可以 (ab)?按以下方式在此处使用捕获组:

DTE.Find.FindWhat = "Container\(""\w+""\)\.(?:(?<f>T)e(?<s>xt)Ctrls|(?<f>L)a(?<s>b)e(?<t>l)Ctrls)\(""(?<ControlName>\w+)""\).Text"
DTE.Find.ReplaceWith = "${f}${s}${t}NameOfControl.Text"

请参阅.NET regex demo

fst填充了必要的文本位,并且只有在相应的替代项匹配时才具有文本。

enter image description here

解决方案 2:使用 MatchEvaluator 进行自定义替换逻辑

您可以使用MatchEvaluator检查匹配的组或组值是什么,然后实现您自己的替换逻辑:

Dim s As String = "Container(""Name1"").TextCtrls(""Name2"").Text" & vbCrLf & "Container(""Name1"").LabelCtrls(""Name2"").Text"
Dim pattern As String = "Container\(""\w+""\)\.(?<test>TextCtrls|LabelCtrls)\(""(?<ControlName>\w+)""\).Text"
Dim result = Regex.Replace(s, pattern, New MatchEvaluator(Function(m As Match)
        If m.Groups("test").Value = "TextCtrls" Then
            Return "TxtNameOfControl.Text"
        Else
            Return "LblNameOfControl.Text"
        End If
    End Function))

输出:

enter image description here

关于regex - 替换为条件 DTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173994/

相关文章:

python - 与 return 语句一起使用 'elif' 或连续的 'if' 语句更好吗?

c# - 为数字符号编写正则表达式

html - 使用正则表达式匿名化 html

Javascript、字符串操作、正则表达式或其他

vb.net - 保存和加载数据 Visual Basic 的简单方法

vb.net - Visual Studio 2012 对象浏览器未使用的引用

php - 正则表达式的数字替换模式问题

vb.net - 在 vb.net 文本框中的光标位置添加文本

r - R 中嵌套 For/If 循环的算法效率

java - 使用 "else"会加速代码的执行吗?