正则表达式在字符串中查找问题

本文关键字:查找 问题 字符串 正则表达式 | 更新日期: 2023-09-27 17:59:52

我有这样的字符串

''你最喜欢的宠物是什么名称''''r''nA.卡特B.狗''r''nC.马D.Snake''r''n22哪个国家生产小麦最多?''''r''nA.澳大利亚B.不丹''r''nC.India D.加拿大.

=========================================

现在我必须通过正则表达式从字符串中找到问题以及选项。

任何人都可以。

我正在像[1-9][.]一样解析这个问题。但我有时会把两个问题合并在一起。

任何人都能提出任何改变吗。

正则表达式在字符串中查找问题

(('d+'..*?'?''r''n)(A'..*?)(B'..*?)(C'..*?)(D'..*?''r''n))

您可以使用此regex,但它假定在最后一个选择之后''r''n有个字符。

我创建了两个可能的正则表达式,这取决于您是否希望问题/答案的数字/字母出现在捕获中。

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()函数的模式来更改使用的模式。

在Python中:

查找问题:

>>> import re
>>> re.findall(r'[1-9][1-9]*'.([^?]*)',s)
['what is your favourite pet name', 'Which country produce wheat most']

我不确定它是否能在孟加拉语中工作,但以下代码在英语中工作正常(至少在您提供的示例中是这样;):

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 regex = new Regex(@"(?<number>[0-9]+)'.(?<question>.+'?)'W+((?<letter>[A-Z])'.(?<answer>'w+)'W*)+");
foreach (Match question in regex.Matches(input))
{
    Console.Write("{0}. ", question.Groups["number"].Captures[0]);
    Console.WriteLine(question.Groups["question"].Captures[0]);
    foreach (Capture answer in question.Groups["answerswer"].Captures)
    {
        Console.WriteLine(answer.Value);
    }
}

它打印:

21. what is your favourite pet name?
Cat
Dog
Horse
Snake
22. Which country produce wheat most?
Australia
Bhutan
India
Canada

我想你可以从那里得到你需要的东西。

这可以帮助:

[0-9]+'.(.*?)'?'s*A'.(.*?)'s*B'.(.*?)'s*C'.(.*?)'s*D'.(.*?)'r'n

使用''r''n来解决问题不是一个好主意。尽管这对你来说应该有效。