.net - 如何用 .net 中的新字符串替换第 n 个正则表达式组?

标签 .net regex

我有一个像这样的管道分隔字符串:

废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话

我想用新的日期替换第 10 节的内容。我能够将旧日期与以下代码相匹配:

'create a group with the first 9 non-pipes followed by a pipe, a group with the old date followed by a pipe, and sub-group of just the old date.
Dim pipeRegEx As New RegularExpressions.Regex("(([^\|]*\|){9})(([^\|]*)\|)")

'the sub-group is the 4th group ordinal in the match GroupCollection
Dim oldDate as String=pipeRegEx.Match(strMessage).Groups(4).Value

但是,我不知道如何用新文本重新调整该组。我试过了:
pipeRegEx.Replace(strMessage, "$4", newDate) 'where newDate is a string var

但这会返回原始消息,就像无法找到第 4 组一样。我无法用匹配的日期替换字符串,因为字符串中有多个日期(orderDate、receiveDate 等),并且可能会偶然匹配其中之一。

有谁知道如何替换这段文字?

在此先感谢您的帮助。

最佳答案

这里没有明显的理由使用正则表达式,使用 strMessage.Split('|') .

string str = "blah|blah|blah|blah|blah|blah|blah|blah|blah|oldDate|blah|blah";
string[] tokens = str.Split('|');
tokens[9] = "newDate";
string newStr = String.Join("|", tokens);

如果您确实需要使用正则表达式,请考虑使用 Regex.Replace(string, string) :
pipeRegEx.Replace(strMessage, "$2" & newDate & "|") 

替换以相反的方式工作 - 您使用组将 token 保留在您的字符串中,而不是将它们移出。

关于.net - 如何用 .net 中的新字符串替换第 n 个正则表达式组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3728643/

相关文章:

c# - .NET 应用程序是否需要 ret 指令?

java - 什么是组件

c# - 上课时不阅读按钮单击时输入的表单

正则表达式查找前面没有逗号的所有引号

Javascript Regexp - 匹配字符串模式,除非字符串在指定标签内

regex - 获取模式中的前一个单词

c# - 异步编程中的线程状态管理

c# - 如何取消 Microsoft ServiceBus MessageReceiver Receive 调用?

Python 正则表达式避免字符串中较早的字符

javascript - 在第一次出现某个模式时停止并可在 JavaScript 中搜索下一行