我有这样的绳子,
\r\n 21.你最喜欢的宠物name?\r\nA.Cat B.Dog\r\nC.Horse D.D.Snake\r\n 22.哪个国家生产小麦most?\r\nA.Australia B.Bhutan\r\nC.India D.Canada。
=====================================
现在,我必须通过正则表达式从字符串中找到问题以及选择。
谁能说笑。
对于这个问题,我正像[1-9][.]一样解析。但我有两个问题有时被合并了。
有人能提出任何改变吗。
发布于 2011-06-22 13:45:36
((\d+\..*?\?\\r\\n)(A\..*?)(B\..*?)(C\..*?)(D\..*?\\r\\n))您可以使用这个regex,但是它假设在最后一个选择之后有\r\n字符。
发布于 2011-06-22 13:58:53
我已经创建了两个可能的正则表达式,取决于您是否希望在捕获中显示问题/答案的数字/字母。
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();它使用regex模式将每个问题解析为一个问题变量,并将相关的答案解析为一个答案列表。您可以通过更改第一个过程中发送给Regex.Matches()函数的模式来更改所使用的模式。
发布于 2011-06-22 13:46:16
在Python中:
找出以下问题:
>>> import re
>>> re.findall(r'[1-9][1-9]*\.([^?]*)',s)
['what is your favourite pet name', 'Which country produce wheat most']https://stackoverflow.com/questions/6440641
复制相似问题