RegEx与日期时间和时区

时间:2012-10-26 20:09:26

标签: regex

我需要一个RegEx来表示日期时间和时区。我正在为PC技术笔记循环一个长字符串,我需要找到日期时间和时区,然后在用户ID后找到下一个空格。时区被硬编码为“东部标准时间 - ”。

我的字符串如下所示:

10/18/2012 4:30 PM Eastern Standard Time - userID1 I rebooted the PC.  10/18/2012 4:30 PM Eastern Standard Time - userID2 The reboot that the other tech performed did not fix the issue.

userID可以是6或8个字符长。我想在每个实例后找到空格的索引并插入换行符。

我使用的是使用C#的ASP .NET 3.5。

感谢。

2 个答案:

答案 0 :(得分:0)

你在这里得到一个例子:Demo

如果您想要反向引用用户名,则只需在(\w{5,8})之前使用[^\.]

答案 1 :(得分:0)

以下是工作代码:

protected string FormatTechNote(string note)
{
    //This method uses a regular expression to find each date time techID stamp
    //in a note on a ticket.  It finds the stamp and then adds spacing for clarity
    //while reading.

    //RegEx for Date Time Eastern Standard Time - techID (6 or 8 characters in techID)
    Regex dateTimeStamp = new Regex(@"((((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00))).([1-9]|1[012]):[0-5][0-9].[AP]M.Eastern Standard Time - [a-z0-9_-]{6,8})");

    MatchCollection matchList = dateTimeStamp.Matches(note);
    if (matchList.Count > 0)
    {
        //If at least one match occurs then insert a new line after that instance.
        Match firstMatch = matchList[0];

        note = Regex.Replace(note, matchList[0].Value, matchList[0].Value + "<br /><br />");

        //If more than one match occurs than insert a new line before and after each instance.
        if (matchList.Count > 1)
        {
            for (int j = 1; j < matchList.Count; j++)
            {
                note = Regex.Replace(note, matchList[j].Value, "<br /><br /><br />" + matchList[j].Value + "<br /><br />");
            }
        }
    }

    //TrackIt uses 5 consecutive spaces for a new line in the note, and 8
    //consecutive spaces for two new lines.  Check for each and then
    //replace with new line(s).

    note = Regex.Replace(note, @"\s{8}", "<br /><br /><br />");

    note = Regex.Replace(note, @"\s{5}", "<br /><br />");

    return note;
}