我已經創建了兩個可能的正則表達式,具體取決於您希望問題/答案的數字/字母是否出現在捕獲中。
Pattern1: (?<Question>\d+\.[^?]+\?)(?:(?:\W*)(?<Answer>[ABCD]\..*?(?=$|(?:\s|\r\n)(?:[ABCD]\.|\d+\.))))*
Pattern2: \d+\.(?<Question>[^?]+\?)(?:(?:\W*)[ABCD]\.(?<Answer>.*?(?=$|(?:\s|\r\n)(?:[ABCD]\.|\d+\.))))*
我假設你在C#想這一點,因爲你標記它爲C#,所以這裏是一些示例代碼可以粘貼到一個新的控制檯應用程序以開始播放:
var input = "\r\n21.what is your favourite pet name?\r\nA.Cat B.Dog\r\nC.Horse D.Snake\r\n22.Which country produce wheat most?\r\nA.Australia B.Bhutan\r\nC.India D.Canada.";
var pattern1 = @"(?<Question>\d+\.[^?]+\?)(?:(?:\W*)(?<Answer>[ABCD]\..*?(?=$|(?:\s|\r\n)(?:[ABCD]\.|\d+\.))))*";
var pattern2 = @"\d+\.(?<Question>[^?]+\?)(?:(?:\W*)[ABCD]\.(?<Answer>.*?(?=$|(?:\s|\r\n)(?:[ABCD]\.|\d+\.))))*";
foreach (Match m in Regex.Matches(input, pattern2))
{
var question = m.Groups["Question"].Value;
var answers = (from Capture cap in m.Groups["Answer"].Captures
select cap.Value).ToList();
Console.WriteLine("Question: {0}", question);
foreach (var answer in answers)
{
Console.WriteLine("Answer: {0}", answer);
}
}
Console.ReadLine();
它使用正則表達式模式將每個問題解析爲問題變量,並將相關答案解析爲答案列表。您可以通過更改發送給第一個foreach中的Regex.Matches()函數的模式來更改使用哪種模式。
總是有4個答案選擇? – scott
[1-9] {1} [0-9]?[。]你可能需要的不止於此,但應該更好地匹配數字 – scott
@scott:你不需要'{1}'。 –