2013-07-31 76 views
16

后,我有文本的长文本和部分检测字正则表达式

你好,我是约翰如何(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)之后的单词?

+0

+1为一个实际的正则表达式问题努力。我把它更多的是它阻止你使用'string.Split(“(1)”)'? – Sayse

+0

是的,我已经做了reg.Spilt(长文本),但我的真正目的是通过做(1),通过做溢出,我将删除文本中的所有(0-9) – user2376998

+0

_replace字(1)带有文本框,你是什么意思?此外,这个问题的标签有点混乱... –

回答

20

使用正回顾后查找((?<=\(\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]); 

顺便说一句,你不需要逃脱\


UPDATE

而不是使用.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? 
+0

嗨感谢您的回复,但请检查我的更新 – user2376998

+0

@ user2376998,你想结果'你好,我是约翰如何(1)(是/是)你? '? – falsetru

+0

是的,这就是我的意思,我的第一步是让这个词消失,然后第二步是用文本框 – user2376998

1

会是这样的工作?

\((?<number>[0-9]+)\)(?<word>\w+) 

已添加的组为便于使用。 :)

+0

永远不要将单词字符与'[a-zA-Z]'匹配 - - 这将使所有外语使用除普通字符之外的任何其他语言失败, en“借来的”条款,如“酌情决定”。 – Lucero

+0

公平点 - 我将编辑使用\ w ... – Shaamaan

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/