我试图从VBA
到VB.NET
迁移一个正则表达式(实用程序)的库,因为(我的总体印象是)它提供了更多支持获得“干净”和可重复使用的代码(包括Regex支持)。VBA到VB.NET - 正则表达式 - System.Text.RegularExpressions - 没有全局修饰符
库是一个factory pattern
重用compiled
正则表达式(用于性能优化目的;不确定选项RegexOptions.Compiled
可以帮助它)。它与一个Lib
组合使用,它保存模式记录(实用程序)并返回一个对象;其中除pattern
还包括modifiers
(作为属性)。
然而,System.Text.RegularExpressions
的RegEx
对象没有一个干净的系统指定flags
/modifiers
......
' VBA
Dim oRegExp As New RegExp
With oRegExp
.Pattern = Pattern
.IgnoreCase = IgnoreCase
.Multiline = Multiline
.Global = MatchGlobal
End With
对战
' VB.NET
Dim opts As RegexOptions = New RegexOptions
If IgnoreCase Then opts = opts Or RegexOptions.IgnoreCase
If Multiline Then opts = opts Or RegexOptions.Multiline
Dim oRegExp As RegEx
oRegExp = New RegEx(Pattern, opts)
'Were can I specify MatchGlobal???
正如我不认为这是一个不对这部分代码的改进,我将依靠应用inline modifiers
代替(these here)(直接嵌入到Pattern
本身),并摆脱包含修饰符作为属性(未包括在示例中)的模式库的对象。
这样...
' This -> "\bpre([^\r\n]+)\b"
' in .NET, can be this -> "\bpre(?<word>\w*)\b"
' as .NET supports named groups
Dim Pattern as String = "(?i)\bpre(?<word>\w*)\b" ' case insensitive
唯一问题是,作为上述VB.NET
例子所示,命名空间System.Text.RegularExpressions
的RegEx
对象似乎不让你改变全球匹配修饰符(和inline modifiers
,逻辑上,不包括global match flag
)。
有关如何处理它的任何想法?
只是假设'MatchGlobal'永远是真的 - 'System.Text。RegularExpressions'没有限制结果集到第一个匹配的概念。只需使用第一场比赛即可。 – Comintern
@Comintern:谢谢你的回答。好吧,我看到了......但是,这似乎并不是一个最佳的解决方案......因为它每次都会获取所有找到的记录,即使您刚需要第一场比赛时也是如此 – rellampec
然后,只需编写您的快递单以便匹配第一个例子 - 即以一行起始行锚'^'。 – Comintern