简体   繁体   English

使用反斜杠作为模式终止符的正则表达式

[英]Regex with a backslash as a pattern terminator

I am trying to get JJ01G3C5-10A6S0 out of : 我正在尝试从中获取JJ01G3C5-10A6S0

\\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. 未处理的异常:System.ArgumentException:解析"[^\\\\].+\\" -模式结尾处的非法\\

Is there no way to have backslash as regex terminator? 有没有办法将反斜杠用作正则表达式终止符?

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. 否则它将尝试匹配所有内容。

假设其unc路径的替代方法:

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

You can use this regex: 您可以使用此正则表达式:

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

RegEx Demo 正则演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM