0

我想将此字符串替换 2000-12-13T13:59:59+12:002000-12-13 13:59:59

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

4

3 回答 3

0

尝试这个

\+\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
}
于 2012-05-30T08:06:19.617 回答
0
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)

资源:在一般的正则表达式上在 .net上,特别是在 C# 上用于测试的简单工具

于 2012-05-30T08:11:28.997 回答
0

使用正则表达式

(.*)\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

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

于 2012-05-30T08:18:38.753 回答