1

I am parsing text and if I encounter a time, I want to split the string. Here is an example:

At 12:30AM I got up. At 11:30PM I went to bed.

My code :

string time = @"[0-9]{2}:[0-9]{2}(A|P)M";
string test = "At 12:30AM I got up. At 11:30PM I went to bed.";
string[] result = Regex.Split(test, time);

foreach(string element in result)
{
   Console.WriteLine(element);
}

What I need to get:

At 12:30AM
I got up. At 11:30PM
I went to bed.

What I get:

At
 A
  I got up. At
 P
  I went to bed.

All that is left of the times are either A or P.

3 Answers 3

1

Change the regex to

([0-9]{2}:[0-9]{2}[AP]M)

Thhe brackets around (A|P) are defining it as the capture group. You need the the whole time string to be captured. So put the brackets around the whole thing.

Sign up to request clarification or add additional context in comments.

4 Comments

Doesn't [A|P] match A, |, and P?
| is a special character. So it won't be matched unless it comes with an escape character.
Ohhk.. New to regex... changed!
Thanks guys, all the answers were very helpful.
1

Because the split function separator is not included in the results.
If you want it to remain as a split element enclose it in parenthesis

string time = @"([0-9]{2}:[0-9]{2}(A|P)M)";

By the way, that's the reason that the 'A' and 'P' were left, because they were enclosed in parenthesis.

1 Comment

Indeed; you want to use [AP] or (?:A|P) if you don't want to capture A or P on their own.
0

Use capturing groups.

string regex=@".+?(?:\b\d{2}:\d{2}(?:AM|PM)|$)";
MatchCollection matches=Regex.Matches(input,regex);
foreach(var match in matches)
    Console.WriteLine(match.Groups[0]);

4 Comments

-1. You really should test your solutions before you post them. All those forward slashes in the regex should be backslashes, the MatchesCollection class name should be MatchCollection, and you should be calling the Matches method instead of Match. And when you've fixed all that, it still won't do what the OP wants.
You're right about the fixes, but the final thing WILL do what the asker wants, or at least what he wrote. He want to include the words before the pattern, as seen in his example.
'Fraid not. You left the semicolon off the first line and you've got the arguments to Matches() reversed. That's why you should always test before posting, even if you're totally confident in the logic of your answer. But your regex still isn't right, as you can see here. Maybe you're thinking of this?
You're right, my mistake. Thanks for correcting me. The site looks pretty cool...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.