我的文字很长,部分文字是
Hello , i am John how (1)are (are/is) you?
我用它来检测 (1)
。
string optionPattern = "[\\(]+[0-9]+[\\)]";
Regex reg = new Regex(optionPattern);
但我被困在这里继续如何检测 (1)
之后找到 are
。
完整代码(感谢 falsetru 让我走到这一步):
string optionPattern = @"(?<=\(\d+\))\w+";
Regex reg = new Regex(optionPattern);
string[] passage = reg.Split(lstQuestion.QuestionContent);
foreach (string s in passage)
{
TextBlock tblock = new TextBlock();
tblock.FontSize = 19;
tblock.Text = s;
tblock.TextWrapping = TextWrapping.WrapWithOverflow;
wrapPanel1.Children.Add(tblock);
}
我假设如果我这样拆分,它会删除 (0-9) 之后的所有单词,但是当我运行它时,它只会删除最后一次检测中 ()
之后的单词。
如您所见,(7) 之后的词消失了,但其余的没有。
如何检测 (1)
之后的 are
?
是否也可以用文本框替换 (1) 之后的单词?
最佳答案
使用正后向查找((?<=\(\d+\))\w+
):
string text = "Hello , i am John how (1)are (are/is) you?";
string optionPattern = @"(?<=\(\d+\))\w+";
Regex reg = new Regex(optionPattern);
Console.WriteLine(reg.Match(text));
打印 are
备选方案:捕获一个组 (\w+)
string text = "Hello , i am John how (1)are (are/is) you?";
string optionPattern = @"\(\d+\)(\w+)";
Regex reg = new Regex(optionPattern);
Console.WriteLine(reg.Match(text).Groups[1]);
顺便说一句,使用 @".."
,你不需要转义 \
.
更新
而不是使用 .Split()
, 只是 .Replace()
:
string text = "Hello , i am John how (1)are (are/is) you?";
string optionPattern = @"(?<=\(\d+\))\s*\w+";
Regex reg = new Regex(optionPattern);
Console.WriteLine(reg.Replace(text, ""));
备选方案:
string text = "Hello , i am John how (1)are (are/is) you?";
string optionPattern = @"(\(\d+\))\s*\w+";
Regex reg = new Regex(optionPattern);
Console.WriteLine(reg.Replace(text, @"$1"));
打印
Hello , i am John how (1) (are/is) you?
关于c# - 检测正则表达式后的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963761/