字符串拆分和替换

时间:2014-08-11 18:37:11

标签: regex vb.net string

我正在尝试根据拆分部分替换字符串。此字符串是一个日期,其中年份应格式化为上标。

EG。 Jan 24, 2014需要在2014年拆分,然后替换为Jan 24, ^2014^,其中2014年是上标。

伪示例:

mydate.Split(" ", 2).Replace("^2014^")

但是,它不应该替换新的分割字符串,而应该是原始的(或原始的副本)。我不能只根据索引编辑,因为格式可能并不总是相同,有时日期可能会扩展到January 24th, 2014,这会破坏传统的索引替换。

3 个答案:

答案 0 :(得分:1)

你可以尝试

(?<=[A-Z][a-z]{2} \d{2}, )(\d{4})

替换为^$1^^\1^

以下是online demo并在regexstorm

上对其进行了测试

如果您想匹配January 24th, 2014,请尝试

([A-Z][a-z]{2,9} \d{2}[a-z]{0,2}, )(\d{4})

替换为$1^$2^

这是demo

答案 1 :(得分:1)

您可以结合使用外观来实现结果。

Regex.Replace(input, "(?<=\d{4})|(?=\d{4})", "^")

<强>解释

(?<=        #  look behind to see if there is:
  \d{4}     #    digits (0-9) (4 times)
)           #  end of look-behind
|           # OR
(?=         #  look ahead to see if there is:
  \d{4}     #    digits (0-9) (4 times)
)           #  end of look-ahead

Live Demo

答案 2 :(得分:0)

通过将日期字符串赋值给Date变量来规范化日期字符串,然后从那里进行格式化。

    Dim dt As Date = "Jan 24, 2014"
    Dim s As String = dt.ToShortDateString.Replace("2014", "^2014^")
    MsgBox(s)
    ' or '
    s = dt.Month.ToString & "/" & dt.Day.ToString & "/^" & dt.Year.ToString & "^"
    MsgBox(s)

IMO RegEx编写一次代码,很难调试/维护。

相关问题