代码之家  ›  专栏  ›  技术社区  ›  dsrekab

如何在.net中用新字符串替换第n个regex组?

  •  4
  • dsrekab  · 技术社区  · 15 年前

    我有一个管道分隔字符串,如下所示:

    布拉|布拉|布拉|布拉|布拉|布拉|布拉|布拉|布拉|旧日期|布拉|布拉|

    我想用新的日期替换第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
    

    但这会返回原始消息,好像找不到第四组。我无法用匹配的日期替换字符串,因为字符串中有多个日期(orderDate、receivedDate等),可能会意外地匹配其中一个日期。

    提前谢谢你的帮助。

    6 回复  |  直到 15 年前
        1
  •  0
  •   Brad    15 年前

    Replace method static . 这意味着它没有考虑您在regx对象pipeRegEx上调用它,而是寻找文本字符串“$4”。

    (?<=expression) 零宽度向前看 (?=expression) 所以只有 匹配 第9项(将其保留为字符串而不是正则表达式)。然后你会打电话给:

    RegEx.Replace(strMessage,pipeRegEx, newDate);
    

    正则表达式语法资源: http://www.regular-expressions.info/reference.html

        2
  •  3
  •   Kobi    15 年前

    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 & "|") 
    

    在里面 你的绳子,不要把它们搬走。

        3
  •  2
  •   msarchet    15 年前

    所以你要做的是,你在叫 Shared RegEx库的版本,您实际上并没有使用RegEx来查找匹配项,而是使用 "$4" 找到一个匹配项,但它不是。这就是为什么你要找回原来的字符串。

    Dim matchedGroups As New System.Text.RegularExpressions.Matches = pipeRegEx.Matches(strMessage)
    
    matchedGroups(9) = "new Date"
    

    然后把你的单子放回去。

        4
  •  2
  •   Alan Moore Chris Ballance    15 年前

    第十个字段,然后将其与新值一起插入。你的正则表达式看起来不错,所以你只需要改变替换参数。像这样:

    newString =  pipeRegEx.Replace(strMessage, "$1" + newDate + "|")
    

    | 因为正则表达式会消耗它。)

        5
  •  1
  •   Michael Eakins    15 年前

    你可以分开来

    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
    
        6
  •  0
  •   dsrekab    15 年前

    好吧,我可以通过布拉德的答案得到答案,而用科比的答案得到答案的方法不同,但是我觉得布拉德的更简洁。

    '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 & "|").