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.
c:\test\test1\test2
c:\test
The problem I am facing is related to the backslash.
What regular expression would I use for this?
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
. , Regex , API File.IO - @dtb.
, , :
, C:\Test C:\Test\Test\Test\Test, , [Drive]:\RootFolder :
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]:\[^\]+"
. , , ...
//numberOfChars is known... string result = inputString.Substring(0, inputString.Length - numberOfChars -1);
string.split() Path.DirectorySeparatorChar, , .
Path , ( ),
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: https://habr.com/ru/post/1725086/More articles:Overload with a generic type parameter? - genericsNokogiri и имя случайного div - rubyIs asp.net webforms a good way to maintain state? - asp.netCan Matlab receive signals from linux? (e.g. SIGIO) - signalsDynamicResource does not work, but does StaticResource do? - wpfHtml/Javascript: Добавить атрибут в элемент управления HTML - javascriptInterface design with canvas - user-interfaceIs it possible to use .NET TransactionScope with Sql Server 2005 without the possibility of promoting DTC? - c #Efficient way to get HttpWebResponse and put it in XDocument - asp.netASP.NET MVC - SWF files not loading - flashAll Articles