我有一个像这样的管道分隔字符串:
废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话|废话
我想用新的日期替换第 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/