1

我正在解析文本,如果遇到时间,我想拆分字符串。这是一个例子:

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

我的代码:

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);
}

我需要得到什么:

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

我得到什么:

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

剩下的时间要么是A,要么是P。

4

3 回答 3

1

因为拆分函数分隔符不包含在结果中。
如果您希望它保留为拆分元素,请将其括在括号中

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

顺便说一句,这就是留下“A”和“P”的原因,因为它们被括在括号中。

于 2013-02-22T05:46:37.760 回答
1

将正则表达式更改为

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

(A|P) 周围的括号将其定义为捕获组。您需要捕获整个时间字符串。所以把括号放在整个事情上。

于 2013-02-22T05:47:24.937 回答
0

使用捕获组。

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]);
于 2013-02-22T05:48:04.213 回答