Remove trailing characters from a path string

I'm new to regex, and I'm going to trim a known number of characters at the end of a line. The line represents the file path, so instead c:\test\test1\test2I would like to remove the trailing characters, leaving c:\test.

The problem I am facing is related to the backslash.

What regular expression would I use for this?

+3
source share
5 answers

Some people, faced with a problem, think: "I know, I will use regular expressions."
Now they have two problems.

, Path :

string GetPathFirstLevel(string path)
{
    while (Path.GetDirectoryName(path) != Path.GetPathRoot(path))
    {
        path = Path.GetDirectoryName(path);
    }

    return path;
}

:

GetPathFirstLevel(@"c:\test\test1\test2")  //  @"c:\test"
GetPathFirstLevel(@"c:\test")              //  @"c:\test"
GetPathFirstLevel(@"c:")                   //  null
+16

. , Regex , API File.IO - @dtb.

, , :

, C:\Test C:\Test\Test\Test\Test, , [Drive]:\RootFolder :

"[a-zA-Z]:\\[^\\]+"

[a-zA-Z] a-z A-Z, .

:

\ (\ - escape-, , - , \, \you put\\- ?)

[^ \] + , \ .

, "unescaped", , @ , :

@"[a-zA-Z]:\[^\]+"
+2

. , , ...

//numberOfChars is known...

string result = inputString.Substring(0, inputString.Length - numberOfChars -1);
+1

string.split() Path.DirectorySeparatorChar, , .

+1

Path , ( ),

Regex.Replace(@"c:\aaa\bb\c", @"^([^\\]*\\[^\\]*)\\.*", @"$1")

To break it:

^      // begins with
(      // start capturing what you want to save
[^\\]* // zero or more characters that are _not_ backslash
\\     // followed by a backslash
[^\\]* // again zero or more characters that are _not_ backslash
)      // stop capturing
\\     // a backslash
.*     // followed by anything

It then $1gives the capture value (i.e. text that matches what was in the first parentheses).

+1
source

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


All Articles