|
I have a path and I want to get the part of a path before my match:
string s1= @"c:\temp\lev1\lev2\lev3\MYWORD\lev5\lev6";
string mtch ="MYWORD"
knowing
s1 and
mtch I want to get the part of path before mtch, so @"c:\temp\lev1\lev2\lev3\".
I tried with RegEx but I don't know how to be elegant.. I'm only able to find MYWORD position and then use the substring.
Is there a smarter solution?
|
|
|
|
|
Regex seems overkill for this, but you can do it with a zero-width positive lookahead assertion[^]:
string s1 = @"c:\temp\lev1\lev2\lev3\MYWORD\lev5\lev6";
string mtch = "MYWORD";
string pattern = "^.*(?=" + Regex.Escape(mtch) + ")";
Console.WriteLine(Regex.Match(s1, pattern).Value);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Also look at the various overloads of Regex.Split() , especially if the initial "match" is more than just a simple string.
|
|
|
|