【问题标题】:Format string with regex and replace value使用正则表达式格式化字符串并替换值
【发布时间】:2021-10-10 12:07:54
【问题描述】:

我有一组日期时间不正确的行。

是否可以使用 Regex.Replace 更正它们?

    Wed2,8-Jul-21 64 53,0 57 
    Thu2, 9-Jul-21 73 60,0 48
    Fri, 30-Jul-21 86 70,0 36
    Sat,31-Jul-21 84 69,0 38
    Sun0, 1-Aug-21 89 73,0 33
    Mon0,2-Aug-21 98 80,0 24 
    Tue0, 3-Aug-21 91 75,0 31
    Wed0,4-Aug-21 92 75,0 30
    foreach (var row in rows)
    {
        Regex rg = new Regex([pattern]);
        rg.Replace(row, [replacement]);
    }

错误的数据在 dateTime 值中;见下文:

这是不正确的:Wed2,8-Jul-21

正确的值为:Wed,28-Jul-21

另外,这是不正确的:Thu2, 9-Jul-21

正确的值为:Thu,29-Jul-21

【问题讨论】:

  • 请显示“正确”的数据是什么。
  • 当然有可能。但是哪些行不正确,期望的结果是什么?
  • @NoahStahl 我刚刚更新了问题。
  • 我刚刚更新了问题@Marco
  • 您可以匹配字符串的索引 3 和 5 并检查它们是数字还是空格,然后使用正则表达式或字符串操作将它们替换为空字符串。我建议学习正则表达式并阅读stackoverflow.com/help/how-to-ask,因为您提出的问题缺乏研究

标签: c# regex


【解决方案1】:

如果唯一的问题是转置字符,那么为您的模式执行此操作:

(Mon|Tue|Wed|Thu|Fri|Sat|Sun)(\d), *(\d)

替换为

$1, $2$3

【讨论】:

  • @Chriss Maurer 谢谢,但主要问题在于第一个示例。请看我对晚安书呆子骄傲的评论。它不工作。
  • @Chris Maurer 我不知道是否必须没有空格,但是在您当前的示例中,Fri 和 30 之间有一个空格 -> “Fri, 30-Jul-21 86 70,0 36"
  • 是的,它会清理它并使每个日期的格式一致。通常在逗号后放置一个空格,但如果不需要,可以将其从替换中删除,并且所有结果在逗号和日期之间始终没有空格。
【解决方案2】:

这是一种方法:

var rows = new[]
{
    "Wed2,8-Jul-21 64 53,0 57",
    "Thu2, 9-Jul-21 73 60,0 48",
    "Fri, 30-Jul-21 86 70,0 36",
    "Sat,31-Jul-21 84 69,0 38",
    "Sun0, 1-Aug-21 89 73,0 33",
    "Mon0,2-Aug-21 98 80,0 24",
    "Tue0, 3-Aug-21 91 75,0 31",
    "Wed0,4-Aug-21 92 75,0 30"
};

var rg = new Regex(@"^(\w{3})\d?, ?(\d.*)");

foreach (var row in rows)
{
    var fixedRow = rg.Replace(row, "$1,$2");
    Console.WriteLine(fixedRow);
}

工作示例:https://dotnetfiddle.net/uAMx06

解释:

一般的想法是匹配你感兴趣的部分,将它们与捕获组一起存储,然后从这些组件中重建一个固定的字符串。

^          Matches the beginning of the input.
(          Starts a capture group. Everything that is matched
             between '(' and ')' will be stored and can be
             referenced with $1.
\w{3}      Matches any word character exactly three times.
)          Closes the capture group.
\d?        Matches a digit 0 or 1 times.
,          Matches a literal ','.
 ?         Matches a space character 0 or 1 times.
(          Starts another capture group, referenced with $2.
\d         Matches a single digit.
.*         Matches any string of characters
)          Closes the last capture group.

【讨论】:

  • 感谢您的回答。但在第一个不应该删除 2. 正确的值是 Wed,28-Jul-21 64 53,0 57
  • 感谢您的精彩解释。我对你的模式做了一个小改动。 ^(\w{3})(\d)?, ?(\d.*) 替换为 $1,$2$3
  • 只是观察到这种正则表达式模式过度匹配错误条件并“纠正”了像 21 年 7 月 30 日星期五这样的情况,使其工作比必须的更努力。我会删除第一个 ?.
猜你喜欢
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2018-07-13
  • 2021-11-29
相关资源
最近更新 更多