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?
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
$ means "Match the end of the string" (the position after the last character in the string).
If your regular expression needs to match characters before or after \y, you can easily specify in the regex whether these characters should be word characters or non-word characters. If you want to match any word, \y\w+\y gives the same result as \m. +\M.
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With