NepSyn14
NepSyn14

Reputation: 163

Difficulty with a Regular Expression C#

I have a line from a text file and I'm trying to create a regular expression to match. This is the line of text.

    2015-01-07 Wed Jan 07 11:03:43.390 Some text here..

My regular expression to match is as follows:

    (?<date>(?<year>(?:\d{4}|\d{2})-(?<month>\d{1,2})-(?<day>\d{1,2})))\s(?<txtEntry1>.*)\s(?<txtEntry2>.*)\s(?<txtEntry3>.*)\s(?<time>(?<hour>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2}):(?<milli>\d{0,3}))\s(?<txtEntry4>.*)\s(?<txtEntry5>.*))

It doesn't match. I'm not concerned about the 'worded' date Wed Jan 07 so I have just left it as a text entry, rather than match it yo to dd/mm/yy. I have been trying to figure it our but with no success. Can anyone see where I have gone wrong?

Upvotes: 0

Views: 74

Answers (2)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

This works for me:

(?<date>(?<year>(?:\d{4}|\d{2}))-(?<month>\d{1,2})-(?<day>\d{1,2}))\s(?<txtEntry1>\S*)\s(?<txtEntry2>\S*)\s(?<txtEntry3>\S*)\s(?<time>(?<hour>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})\.(?<milli>\d{0,3}))\s(?<txtEntry4>.*)

not sure about your textentry5 though

Found 1 match:
2015-01-07 Wed Jan 07 11:03:43.390 Some text here.. has 13 groups:
2015-01-07 (date)
2015 (year)
01 (month)
07 (day)
Wed (txtEntry1)
Jan (txtEntry2)
07 (txtEntry3)
11:03:43.390 (time)
11 (hour)
03 (minutes)
43 (seconds)
390 (milli)
Some text here.. (txtEntry4)
String literals for use in programs:
C#
@"(?<date>(?<year>(?:\d{4}|\d{2}))-(?<month>\d{1,2})-(?<day>\d{1,2}))\s(?<txtEntry1>\S*)\s(?<txtEntry2>\S*)\s(?<txtEntry3>\S*)\s(?<time>(?<hour>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})\.(?<milli>\d{0,3}))\s(?<txtEntry4>.*)"

Upvotes: 1

Jamiec
Jamiec

Reputation: 136094

There are 2 problems with your regular expression

  1. There is no pattern specified for the capture group month (now updated)
  2. You have used a colon, instead of a period for the separator between second and millisecond (?<seconds>\d{2}):(?<milli>\d{0,3}))

Upvotes: 2

Related Questions