inside
inside

Reputation: 3177

Regex with a backslash as a pattern terminator

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?

Upvotes: 1

Views: 475

Answers (3)

AnotherParker
AnotherParker

Reputation: 790

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.

Upvotes: 3

Alex K.
Alex K.

Reputation: 175748

Alternative assuming its a unc path:

string unc_server_name = new Uri(@"\\JJ01G3C5-10A6S0\C$\2015\Mar\24\").Host;

Upvotes: 3

anubhava
anubhava

Reputation: 784898

You can use this regex:

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

RegEx Demo

Upvotes: 2

Related Questions