Reputation: 1071
I have a long text and part of the text is
Hello , i am John how (1)are (are/is) you?
I used this to detect (1)
.
string optionPattern = "[\\(]+[0-9]+[\\)]";
Regex reg = new Regex(optionPattern);
But I got stuck here at continue on how to detect after (1)
to find are
.
Full code ( thanks to falsetru for bringing me this far) :
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);
}
I assume if I split like this, it will remove all the words after (0-9), however when I run it it only removes the word after ()
in the last detection.
As you can see the word after (7) is gone but the rest is not.
How do I detect the are
after the (1)
?
Is it possible to replace the word after (1) with a textbox too?
Upvotes: 15
Views: 776
Reputation: 5650
Would something like this work?
\((?<number>[0-9]+)\)(?<word>\w+)
Groups already added for ease of use. :)
Upvotes: 1
Reputation: 369364
Use positive lookbehind lookup ((?<=\(\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));
prints are
Alternative: capture a group (\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]);
BTW, using @".."
, you don't need to escape \
.
UPDATE
Instead of using .Split()
, just .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, ""));
alternative:
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"));
prints
Hello , i am John how (1) (are/is) you?
Upvotes: 19
Reputation: 32571
If you want to replace the text (I'm assuming that you are looking for some HTML), try:
var input = "Hello , i am John how (1)are (are/is) you?";
var output= Regex.Replace(input, @"(?<=\(\d*\))\w*", m => {
return "<input type='text'/>";
});
And this is how the output is being rendered: http://jsfiddle.net/dUHeJ/.
Upvotes: 0
Reputation: 2145
Try this,
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);
in string final remaining text after (1) will store.
Upvotes: 0