Given the string \\Server\Folder\File.EXT, what is the regular expression to return \\Server\ as the match? I tried ^\\\\(.*)\\, but that still allows for a backslash in the middle of the match, so I get \\Server\Folder\ as the match, not \\Server\. Within the group I need to match any number of characters other than \ I think.
Asked
Active
Viewed 44 times
1
Gordon
- 5,265
- 2
- 28
- 58
1 Answers
3
Use negated character class instead of . in your regex.
^\\\\([^\\]*)\\
Or make it non-greedy using ?
^\\\\(.*?)\\
Pranav C Balan
- 110,383
- 23
- 155
- 178
-
1Aha, I was just now trying the negation behind, not in front. And, curious since both approaches work, is one preferred over another in this scenario? Or are they both equally valid? – Gordon Dec 21 '16 at 17:48
-
Well, there where two answers there. ^\\\\([^\\]*)\\ works, and so does ^\\\\(.*?)\\. The latter, the "Make it non greedy" solution seems like the better approach, but I don't know enough to be sure. And the supposed duplicate answer doesn't really seem to explain the difference in function either. – Gordon Dec 21 '16 at 17:55
-
@Gordon : http://stackoverflow.com/a/41269468/3037257 – Pranav C Balan Dec 21 '16 at 18:50