Regex + Delete all text before the match

I am trying to find a way to remove all text in a string before matching in Regex. I am coding this in C #.

For example, if the string is "hello, test matching", and the template is "test", I would like the final result to be a "test comparison" (that is, delete everything before the test).

Any thoughts? Thanks!

EDIT: I probably should have been more specific in my example after reading your answers (and thanks for them). I like the lookahead method, but I simplified my example. To complicate the situation, usually the lines look like this:

"hello, allAfter conformance test"

So, if I use the "test" pattern, it will catch the first. What is my goal - to replace the entire text after the second match. That is: the result is in "test everythingAfter" .... Sorry.

+6
source share
3 answers

* 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; 
0
source

You can use positive lookup to match the string, but not capture it:

 (?=test) 

So, you want to record the material until the last occurrence of the test:

 ^.*(?=test) 

If you want to make it so that this is the first occurrence of the test, use lazy matching:

 ^.*?(?=test) 
+7
source

For a simple solution, simply replace "start-of-line anything test" with "test":

 newString = Regex.Replace(oldString, "^.*test", "test"); 

Since * greedy, this will replace as many as possible, i.e. a test b test c becomes test c . To replace as little as possible, use *? instead of * .

If you want to avoid duplication of the search word, you can use the Assertion with a positive expectation of zero width :

 newString = Regex.Replace(oldString, "^.*(?=test)", ""); 
+5
source

Source: https://habr.com/ru/post/905856/


All Articles