【问题标题】:How to use .net regex to replace this string?如何使用 .net 正则表达式替换此字符串?
【发布时间】:2012-05-30 08:01:25
【问题描述】:

我想替换这个字符串 2000-12-13T13:59:59+12:00 成为 2000-12-13 13:59:59

这可能吗?,我不能使用通用替换是因为这个值是和其他字符串/消息混合在一起的,所以我需要搜索模式来替换。

【问题讨论】:

  • 您能否提供更多您的作品示例,如果它们与您提供的相同。我们可以通过编写我们自己的字符串解析器来轻松归档它:)

标签: .net regex replace


【解决方案1】:
MessageBox.Show(Regex.Replace(
    @"2000-12-13T13:59:59+12:00",
    @"\b(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})[+-]\d{2}:\d{2}\b",
    @"$1 $2"
));

upd:在模式周围添加单词边界、一些解释和一些链接

\b                - word boundary (not to match "12000-12-13T..." or "X2000-12-13T..." etc, but still to match "(2000-12-13T..." and the like, optional)
(                 - start first capturing ($1)
\d{4}-\d{2}-\d{2} - date; 4 digits, dash, 2 digits, dash, 2 digits (\d for digit, {N} for exactly N of them)
)                 - end first capturing ($1)
T                 - literal "T"
(                 - start second capturing ($2)
\d{2}:\d{2}:\d{2} - time; 2 digits, colon, 2 digits, colon, 2 digits
)                 - end second capturing ($2)
[+-]              - utc offset sign; any of literal "+" or "-" (be careful with "-" inside [], if between other characters it defines range, like [a-z])
\d{2}:\d{2}       - utc offset; 2 digits, colon, 2 digits
\b                - word boundary (not to match "...+12:000" or "...+12:00a" etc, optional)

资源:on regex in generalon .neton C# in particularsimple tool for testing

【讨论】:

  • 谢谢!这是工作!当我四处搜索但没有看到可以用 $1 $2 替换时,您能否指导我参考更完整的正则表达式参考。
  • 添加了一些细节。我希望这会有所帮助。
【解决方案2】:

试试这个

\+\d{2}:\d{2}$

代码

string resultString = null;
try {
    resultString = Regex.Replace(subjectString, @"\+\d{2}:\d{2}$", "$${retain}", RegexOptions.IgnoreCase);
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

【讨论】:

    【解决方案3】:

    使用正则表达式

    (.*)\s(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})\+\d{2}:\d{2}\s(.*)
    

    还有下面的代码

    var regexPattern = @"(.*)\s(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})\+\d{2}:\d{2}\s(.*)";
    
            var dateString = "Some text here 2000-12-13T13:59:59+12:00 And some more text here";
    
            var formattedString = Regex.Replace(dateString, regexPattern, "$2 $3", RegexOptions.IgnoreCase);
    

    会输出

    2000-12-13 13:59:59
    

    正则表达式相当严格,因此您应该能够从其他文本中获取它,只要它始终采用该格式 - 如果格式完全改变(时间或日期中的单个数字),那么它不会匹配,但是如果没有上下文就很难说这是否是一个问题。它还假设该模式在文本中只出现一次,并且它有一个前后空格。

    【讨论】:

    • 这使用空格作为分隔符,不适用于分号、括号等。此外,这将替换所有字符串,不仅是时间,这通常不是所需的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2015-02-27
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多