Regular expression to extract everything up to the first slash

I need a regex to get the first part of the string first before the first slash ().

For example, in the following:

C: \ MyFolder \ MyFile.zip

I need the " C: " part

Another example:

somebucketname \ MyFolder \ MyFile.zip

I need " somebucketname "

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

for instance

somebucketname \ MyFolder \ MyFile.zip

will return

MyFolder \ MyFile.zip .

+3
source share
6 answers

( ), :

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

:

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

.NET. , .NET , - .

, "", , . - "(? XxSome Regex Expressionxx). 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

, .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(@"\", "");
+2

\chars

[^\\]*
+1

, "" "?"...

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

Divide by a slash, then get the first element

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

Source: https://habr.com/ru/post/1736507/


All Articles