我有一个这样的管道分隔字符串:
blah | blah | blah | blah | blah | blah | blah | blah | oldDate | blah | blah |
我想用新的日期替换第十部分的内容。我可以使用以下代码匹配旧日期:
'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
但这会返回原始消息,就像找不到第四组一样。我无法用匹配的日期替换字符串,因为字符串中有多个日期(orderDate,receivedDate等),并且可能偶然匹配其中一个。
有人知道如何替换此文本吗?
在此先感谢您的帮助。
最佳答案
Replace method是static
。这意味着它没有考虑您在RegEx对象pipeRegEx上调用它的事实,而是在寻找文字字符串“ $ 4”。
我将使用零宽度后缀(?<=expression)
和零宽度前瞻(?=expression)
重写表达式,以使其仅匹配第9个项目(并将其保留为字符串而不是RegEx)。然后,您将调用:
RegEx.Replace(strMessage,pipeRegEx, newDate);
RegEx语法资源:http://www.regular-expressions.info/reference.html