代码之家  ›  专栏  ›  技术社区  ›  Alex

正则表达式来检索第一个斜杠之前的所有内容

  •  3
  • Alex  · 技术社区  · 14 年前

    我需要一个正则表达式来得到字符串的第一部分, 之前 第一个斜杠()。

    C:\MyFolder\MyFile.zip文件

    我需要的是“ "

    另一个例子:

    我需要“ somebucketname公司 "

    somebucketname\MyFolder\MyFile.zip文件

    .

    6 回复  |  直到 14 年前
        1
  •  4
  •   Andrew Hare    14 年前

    您不需要正则表达式(对于这样一个简单的问题,它会带来太多的开销),请尝试以下方法:

    yourString = yourString.Substring(0, yourString.IndexOf('\\'));
    

    为了在第一个斜杠之后找到所有的东西,你可以这样做:

    yourString = yourString.Substring(yourString.IndexOf('\\') + 1);
    
        2
  •  3
  •   Peter Mortensen Abd Al-Kareem Attiya    14 年前

    使用.NET正则表达式引擎可以非常清楚地处理这个问题。NET正则表达式的真正优点是能够使用命名组捕获。

    使用命名组捕获允许您为您感兴趣的正则表达式的每个部分定义一个名称,以便稍后引用以获取其值。组捕获的语法是“(?xxx一些正则表达式xx)。还要记住包括 System.Text.RegularExpressions 在项目中使用正则表达式时导入语句。

    好好享受!

    //正则表达式

      string _regex = @"(?<first_part>[a-zA-Z:0-9]+)\\{1}(?<second_part>(.)+)";
    
      //Example 1
      {
        Match match = Regex.Match(@"C:\MyFolder\MyFile.zip", _regex, RegexOptions.IgnoreCase);
        string firstPart = match.Groups["first_part"].Captures[0].Value;
        string secondPart = match.Groups["second_part"].Captures[0].Value;
      }
    
      //Example 2
      {
        Match match = Regex.Match(@"somebucketname\MyFolder\MyFile.zip", _regex, RegexOptions.IgnoreCase);
        string firstPart = match.Groups["first_part"].Captures[0].Value;
        string secondPart = match.Groups["second_part"].Captures[0].Value;
       }
    
        3
  •  2
  •   Andy Shellam    14 年前

    您知道.NET的文件处理类在这方面做得非常出色,对吧?

    例如,在上一个示例中,您可以执行以下操作:

    FileInfo fi = new FileInfo(@"somebucketname\MyFolder\MyFile.zip");
    string nameOnly = fi.Name;
    

    第一个例子是:

    FileInfo fi = new FileInfo(@"C:\MyFolder\MyFile.zip");
    string driveOnly = fi.Root.Name.Replace(@"\", "");
    
        4
  •  1
  •   Dark Castle    14 年前

    匹配所有非字符

    [^\\]*
    
        5
  •  0
  •   Software.Developer    14 年前

    下面是使用“贪婪”运算符“?”。。。

            var pattern = "^.*?\\\\";
            var m = Regex.Match("c:\\test\\gimmick.txt", pattern);
            MessageBox.Show(m.Captures[0].Value);
    
        6
  •  0
  •   ghostdog74    14 年前

    words = s.Split('\\');
    words[0]