Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex + Remove all text before match

Tags:

c#

regex

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", and the pattern is "test", I would like the final result to be "test matching" (ie remove everything before test).

Any thoughts? Thanks!

EDIT: I probably should have been a bit more specific in my example after reading your responses (and thanks for them). I like the lookahead method, but I oversimplified my example. To make things more difficult, usually the strings look like:

"hello, test matching test everythingAfter"

So if I use the pattern "test", it will catch the first one. What my goal is, is to replace all text after the second match. Ie: result in "test everythingAfter".... Sorry about that.

like image 854
keynesiancross Avatar asked Jan 12 '12 19:01

keynesiancross


1 Answers

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)
like image 106
Donald Miner Avatar answered Oct 05 '22 20:10

Donald Miner