开发者

Regular expression to retrieve everything before first slash

I need a regular expression to basically get the first part of a string, before the first slash ().

For example in the following:

C:\开发者_如何学JAVAMyFolder\MyFile.zip

The part I need is "C:"

Another example:

somebucketname\MyFolder\MyFile.zip

I would need "somebucketname"

I also need a regular expression to retrieve the "right hand" part of it, so everything after the first slash (excluding the slash.)

For example

somebucketname\MyFolder\MyFile.zip

would return

MyFolder\MyFile.zip.


You don't need a regular expression (it would incur too much overhead for a simple problem like this), try this instead:

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

And for finding everything after the first slash you can do this:

yourString = yourString.Substring(yourString.IndexOf('\\') + 1);


This problem can be handled quite cleanly with the .NET regular expression engine. What makes .NET regular expressions really nice is the ability to use named group captures.

Using a named group capture allows you to define a name for each part of regular expression you are interested in “capturing” that you can reference later to get at its value. The syntax for the group capture is "(?xxSome Regex Expressionxx). Remember also to include the System.Text.RegularExpressions import statement when using regular expression in your project.

Enjoy!

//Regular expression

  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;
   }


You are aware that .NET's file handling classes do this a lot more elegantly, right?

For example in your last example, you could do:

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

The first example you could do:

FileInfo fi = new FileInfo(@"C:\MyFolder\MyFile.zip");
string driveOnly = fi.Root.Name.Replace(@"\", "");


This matches all non \ chars

[^\\]*


Here is the regular expression solution using the "greedy" operator '?'...

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


Split on slash, then get first item

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜