替换正则表达式中的多个捕获组

发布于 2025-01-03 20:15:25 字数 749 浏览 1 评论 0原文

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

VB2005: I've been looking at regex for some hours now and cant seem to get my head around the .Replace for my case. I'm looking for two fields and then I want to replace those fields with new values. So my string looks like so:

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

My regex is

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)

and that works well and it captures my two fields.
Now I have new values

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

But cant seem to figure out how to replace the two values in one swoop

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

What do I put in MyRegexReplace? This is a simple two value replace but Im going to have possibly more so was thinking there has got to be a way to do this but need help.

Thanks
AGP

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱成瘾 2025-01-10 20:15:25

由于您有 2 个不同的值要交换到这 2 个字段中,您难道不想使用 2 个单独的正则表达式操作吗?

但如果您想使用一个 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

Since you have 2 distinct values to swap into those 2 fields, wouldn't you want to use 2 separate Regex operations?

But if you want to use one Regex operation, you could use a 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文