3

VB2005:我已经研究了几个小时的正则表达式,似乎无法理解 .Replace 的情况。我正在寻找两个字段,然后我想用新值替换这些字段。所以我的字符串看起来像这样:

Dim myInputString as string ="RTEMP                 MIN<240  MAX<800"

我的正则表达式是

dim ptn as string = "RTEMP\s{17}MIN<(?<min>(\d|\s){1,3})\s{1,3}MAX<(?<max>(\d|\s){1,3})\s{1,12}"
Dim MyRegex As Regex = New Regex(ptn, RegexOptions.IgnoreCase)

这很好用,它占据了我的两个领域。现在我有了新的价值观

dim newMin as integer = 300
dim newMax as integer = 999

但似乎无法弄清楚如何一口气替换这两个值

Dim result As String = MyRegex.Replace(myInputString, MyRegexReplace)

我在 MyRegexReplace 中放了什么?这是一个简单的二值替换,但我可能会有更多,所以我认为必须有一种方法可以做到这一点,但需要帮助。

感谢 AGP

4

1 回答 1

0

由于您有 2 个不同的值可以交换到这 2 个字段中,您不想使用 2 个单独的 Regex 操作吗?

但是如果你想使用一个 Regex 操作,你可以使用 MatchEvaluator:

Dim result As string = MyRegex.Replace(myInputString, ReplaceField)

Private Function ReplaceField(match As Match) As String
    ' Use the Index property of the Match to determine what value to use as replacement
End Function
于 2012-02-09T07:46:26.437 回答