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

我有一个像这样的管道分隔字符串: 等等|等等|等等|等等|等等|等等|等等|等等|等等| oldDate |等等|等等| 我想用新的日期替换第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,receivedDate等),并且可能偶然匹配其中一个日期。 有谁知道如何替换这个文字? 在此先感谢您的帮助。     
已邀请:
替换方法是
static
。这意味着它没有考虑你在theRegEx对象pipeRegEx上调用它而是查找文字字符串“$ 4”的事实。 我会使用零宽度后视
(?<=expression)
和零宽度前ѭ4重写我的表达式,以便它只匹配第9项(并将其保留为字符串而不是RegEx)。然后你会打电话:
RegEx.Replace(strMessage,pipeRegEx, newDate);
RegEx语法资源:http://www.regular-expressions.info/reference.html     
这里没有明显的理由使用正则表达式,使用
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 & "|") 
替换工作相反 - 您使用组来保持字符串中的标记,而不是将它们移出。     
所以你正在做的就是这个,你在正则表达式上调用RegEx库的
Shared
版本,你实际上并没有使用你的正则表达式找到匹配,而是使用
"$4"
找到一个匹配,它不是。这就是为什么要取回原始字符串的原因。 我会做这样的事情,以便用新的日期替换相应的组
Dim matchedGroups As New System.Text.RegularExpressions.Matches = pipeRegEx.Matches(strMessage)

matchedGroups(9) = "new Date"
然后将您的列表重新组合在一起。     
你要落后了。你想要做的是捕获第十个字段之前的所有内容,然后将其与新值一起重新插入。你的正则表达式看起来很好,所以你只需要更改替换参数。像这样的东西:
newString =  pipeRegEx.Replace(strMessage, "$1" + newDate + "|")
(你必须重新插入
|
,因为正则表达式会消耗它。)     
你可以使用拆分
Dim str As String = "blah|blah|blah|blah|blah|blah|blah|blah|blah|oldDate|blah|blah|"
Dim obj As Object = str.Split("|")
obj(9) = "new date" 
然后
str = strings.join(obj, "|")
要么
for each obj1 as object in obj
   str&= obj1
next
    
好吧,我能够在布拉德的答案的帮助下获得解决方案,并通过不同的方式获得Kobi答案的解决方案,但我觉得布拉德更简洁。
'This regex does a look behind for the string that starts with 9 sections
'and another look ahead for the next pipe.  So the result of this regex is only
'the old date value.
Dim pipeRegEx As New RegularExpressions.Regex("(?<=^(([^|]*|){9}))([^|]*)(?=|)")

'I then store the old date with:
oldDate=pipeRegEx.Match(strMessage).Value

'And replace it with the new date:
strMessage=pipeRegEx.Replace(strMessage, newDate & "|").
    

要回复问题请先登录注册