如何在c#中匹配模式并提取出其中的一部分?
本文关键字:提取 一部分 模式 | 更新日期: 2023-09-27 18:06:46
我有以下文本在一个字符串中,总是以"?"结尾。
"Which of the following can be abc def ghi?"
"Which of the following can be hello?"
谁能告诉我如何检查这个文本是否包含:
"Which of the following <any string of text here>?"
如果它包含了这个那么我怎么能得到文本"abc def "answers"hello"
const string constantValue = "Which of the following can be ";
var theString = "Which of the following can be abc def ghi?";
var index = theString.IndexOf(constantValue);
string result = "";
if (index > -1)
result = theString.Substring(constantValue.Length,
theString.Length - constantValue.Length - index - 1);
编辑:这个正则表达式应该匹配来自其他问题的所有输入:
var text = "1 - Which of the following is a aa mmm zz?'n" +
"2 - Which of the following is true?'n" +
"3 - Which of the following can be aa mmm zz?'n" +
"4 - Which of the following are correct?'n" +
"5 - What will be the result when aa mmm zz?'n" +
"6 - What will result when aa mmm zz?'n" +
"7 - Which are aa mmm zz?'n" +
"8 - What can be said about aa mmm zz?'n";
var regex = @"What (can be said about |will (be the )?result when )(?<result>.*?)'?|Which (of the following )?(can be|are|is|is a) (?<result>.*?)[?:]";
var matches = Regex.Matches(text, regex);
foreach (Match match in matches)
{
Console.WriteLine("result: " + match.Groups["result"]);
}
您可以使用String.StartsWith()来检查子字符串是否存在。
您可以使用Split()根据指定的子字符串拆分字符串。
你也可以使用正则表达式,如果你理解它们(我不懂…)
如果您只想匹配整个输入字符串,并确保输入字符串以问题的开头开始,则使用此:
static string ExtractQuestionObject(string question)
{
const string pattern = "Which of the following ";
if (question.StartsWith(pattern, StringComparison.CurrentCultureIgnoreCase)
&& question.EndsWith("?"))
return question.Substring(pattern.Length, question.Length - pattern.Length - 1);
else
return null;
}
如果你想在输入的任何地方找到问题,使用:
static string FindQuestionObject(string text)
{
const string pattern = "Which of the following ";
int questionStart = text.IndexOf(pattern);
if (questionStart >= 0)
{
int questionMark = text.IndexOf('?', questionStart);
if (questionMark > questionStart)
return text.Substring(questionStart + pattern.Length,
questionMark - questionStart - pattern.Length);
}
return null;
}
如果您想使用正则表达式在一次调用中匹配所有字符串,请使用:
static string[] FindQuestionObjects(string text)
{
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(
@"Which of the following ([^'?]+)'?",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.MatchCollection mc = re.Matches(text);
string[] result = new string[mc.Count];
for(int i = 0; i < result.Length; i++)
result[i] = mc[i].Groups[1].Value;
return result;
}
if (str.Length > "Which of the following".Length)
{
Console.WriteLine(str.Replace("Which of the following", "").Replace("can be" , "").Trim());
}