c# - 检测正则表达式后的单词

标签 c# regex

我的文字很长,部分文字是

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) 之后的所有单词,但是当我运行它时,它只会删除最后一次检测中 () 之后的单词。

enter image description here

如您所见,(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/

相关文章:

c# - XmlReader.ReadSubTree() 始终返回 NONE

c# - 命名空间 'Windows' 中不存在类型或命名空间名称 'System'

c# - 当前文件夹中的 .dll 出现 DllNotFoundException

C# regex 无法通过管道分隔符拆分字符串

regex - xsd:SimpleType:如何将属性限制为特定值和正则表达式值

c# - 尝试使用 psexec (c#) 在远程运行 .exe 时出现问题?

c# - knockout 排序似乎没有做任何事情

java - 正则表达式选择 XML 标签之间的空格

Python 正则表达式匹配直到多行字符

java - 大括号内的正则表达式值