I\'m trying to figure out a way to remove all text in a string before match in Regex. I\'m coding this in C#.
For example, if the string is \"hello, test matching\
*Updated, using matchcollection
string test = "hello, test matching";
string regexStrTest;
regexStrTest = @"test\s\w+";
MatchCollection m1 = Regex.Matches(test, regexStrTest);
//gets the second matched value
string value = m1[1].Value;
For a simple solution, just replace "start-of-line anything test" with "test":
newString = Regex.Replace(oldString, "^.*test", "test");
Since *
is greedy, this will replace as much as possible, i.e. a test b test c
will become test c
. To replace as little as possible, use *?
instead of *
.
If you want to avoid duplicating the search word, you can use a Zero-width positive lookahead assertion:
newString = Regex.Replace(oldString, "^.*(?=test)", "");
You can use positive lookahead to match a string but not capture it:
(?=test)
So you want to capture the stuff before the last occurrence of test:
^.*(?=test)
If you want to make it so that it is the first occurrence of test, use lazy matching:
^.*?(?=test)