检测正则表达式后面的单词

15

我有一段很长的文本,其中一部分内容是:

你好,我是John,你(1)怎么样?

我使用这个来检测(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)后面的单词?


+1 如果你有一个实际的正则表达式问题并且付出了努力。我猜你不使用 string.Split("(1)") 是因为还有其他原因吧? - Sayse
是的,我已经使用reg.Spilt(长文本)了,但我的真正目的是获取(1)后面的单词,通过进行拆分,我正在删除文本中的所有(0-9)。 - user2376998
将(1)后面的单词替换为一个文本框,你是什么意思?此外,这个问题的标签有点混乱... - Alex Filipovici
4个回答

19
(?<=\(\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?

如果我有一段非常长的文本,其中包含许多(1),(2)...,我使用replace(text, ""),它会找到所有模式并替换为空白吗? - user2376998
1
@user2376998,你的文本在括号数字和单词之间有空格。我更新了代码(目前仅更新部分)。看看吧。 - falsetru
1
@user2376998,@"(?<=\(\d+\)).*?(?=\()" - falsetru
1
@user2376998,如果您不想包含空格,请使用@"(?<=\(\d+\)\s*)\w+(?=\s*\()" - falsetru
1
@user2376998,@"(?<=\(\d+\)).*?(?=\()"将会。 - falsetru
显示剩余10条评论

1
“这样的东西能行吗?”
\((?<number>[0-9]+)\)(?<word>\w+)

已经添加了组以便于使用。 :)


永远不要使用[a-zA-Z]来匹配单词字符 - 这将无法匹配任何使用非纯字符或甚至是“借用”术语(如“à discretion”)的外语。 - Lucero

0

试试这个,

string text = "Hello , i am John how (1)are (are/is) you?";
string optionPattern = "[\\(]+[0-9]+[\\)]";
Regex reg = new Regex(optionPattern);
Match t = reg.Match(text);
int totallength = t.Index + t.Length;
string final = text.Substring(totallength,text.length-totallength);

在字符串中,括号(1)后的最终剩余文本将被存储。


0
如果你想替换文本(我假设你正在寻找一些HTML),可以尝试以下步骤:
var input = "Hello , i am John how (1)are (are/is) you?";
var output= Regex.Replace(input, @"(?<=\(\d*\))\w*", m => {
    return "<input type='text'/>";
});

这是输出的呈现方式:http://jsfiddle.net/dUHeJ/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接