1

I am trying to get JJ01G3C5-10A6S0 out of :

\\JJ01G3C5-10A6S0\C$\2015\Mar\24\

with

Regex reg = new Regex("[^\\\\].+\\");

Note: I cannot assume that the value will be specifically in this format, so the only way for me to terminate the string is to assume that it starts with double backslash \\ then some data ... and then terminated by one backslash \

However this throws me:

Unhandled Exception: System.ArgumentException: parsing "[^\\].+\" - Illegal \ at the end of pattern.

Is there no way to have backslash as regex terminator?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
inside
  • 3,047
  • 10
  • 49
  • 75

3 Answers3

3

when you're writing a regex, it's best to use verbatim string literals, that is, prefix an @ to the double-quoted string. This prevents the compiler from treating the backslash as the escape character. Without the @ you need to double all the backslashes.

Also you don't need to use the square brackets. Those are for character classes.

Regex reg = new Regex("^\\\\\\\\.+\\\\");

or equivalently (and more understandably)

Regex reg = new Regex(@"^\\\\.+?\\");

This parses as:

  • ^ start of line
  • \\ meaning a literal backslash
  • \\ meaning another literal backslash
  • .+? meaning more than one of any character
  • \\ meaning another literal backslash

The +? notation means it is non-greedy, it matches as few characters as possible in order to make the whole thing match. Otherwise it will try to match everything.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
AnotherParker
  • 789
  • 5
  • 16
  • Your explanation of the parts of the regular expression doesn't match up with the regular expression. Specifically `$` is not the start of a line `^` is (as you have it in your regular expression) and you are not using `.+?` in the regular expression. – juharr Mar 25 '15 at 18:40
  • What are you talking about? None of my regular expressions have a $ in them, nor does the OP's regex. – AnotherParker Mar 25 '15 at 18:41
  • 2
    I just fixed that. Now I can upvote the first answer that actually answers the question. – Alan Moore Mar 25 '15 at 18:42
  • Thanks @AlanMoore I have no idea how my example regex got so twisted. – AnotherParker Mar 25 '15 at 18:43
  • But there's one more problem. The OP is trying to extract the text without the backslashes, so you need to capture the `.+?` and show how to retrieve that part. – Alan Moore Mar 25 '15 at 18:57
3

Alternative assuming its a unc path:

string unc_server_name = new Uri(@"\\JJ01G3C5-10A6S0\C$\2015\Mar\24\").Host;
Alex K.
  • 171,639
  • 30
  • 264
  • 288
2

You can use this regex:

Regex regex = new Regex(@"(?<=\\\\)[^\\]*(?=\\)");

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643