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 に答える