[英]Regex - C# - Get non matching part of string
我在下面寫的正則表達式模式匹配“FinalFolder”之前的字符串。 如何在匹配正則表達式的字符串之后獲取文件夾名稱(在本例中為“FinalFolder”)?
編輯:很確定我的正則表達式錯了。 我的意圖是匹配“C:\\ FolderA \\ FolderB \\ FolderC \\ FolderD \\ Test 1.0 \\ FolderE \\ FolderF”,然后找到該文件夾。 所以,在這種情況下,我要找的文件夾是“FinalFolder”
[TestMethod]
public void TestRegex()
{
string pattern = @"[A-Za-z:]\\[A-Za-z]{1,}\\[A-Za-z]{1,}\\[A-Za-z0-9]{1,}\\[A-Za-z0-9]{1,}\\[A-Za-z0-9._s]{1,}\\[A-Za-z]{1,}\\[A-Za-z]{1,}";
string textToMatch = @"C:\FolderA\FolderB\FolderC\FolderD\Test 1.0\FolderE\FolderF\FinalFolder\Subfolder\Test.txt";
string[] matches = Regex.Split(textToMatch, pattern);
Console.WriteLine(matches[0]);
}
還有很多其他的提示和建議會引導您獲得所需的文件夾,我建議您考慮它們。 但是,因為看起來你仍然可以從學習更多正則表達式技能中受益,所以這就是你要求的答案: 獲得不匹配的字符串部分 。
讓我們假設您的Regex實際上匹配給定的路徑,例如: [A-Za-z]:\\\\[A-Za-z]+\\\\[A-Za-z]+\\\\[A-Za-z0-9]+\\\\[A-Za-z0-9]+\\\\[A-Za-z0-9._\\s]+\\\\[A-Za-z]+\\\\[A-Za-z]+
您可以獲取匹配的字符串,其位置和長度,然后確定原始源字符串中下一個文件夾名稱的起始位置。 但是,您還需要確定下一個文件夾名稱的結束位置。
MatchCollection matches = Regex.Matches(textToMatch, pattern);
if (matches.Count > 0 ) {
Match m = matches[0];
var remaining = textToMatch.Substring(m.Index + m.Length);
//Now find the next backslash and grab the leftmost part...
}
這回答了您最常見的問題, 但這種方法會破壞使用正則表達式的整個效用。 相反,只需擴展您的模式以匹配下一個文件夾!
正則表達式模式已經提供了捕獲匹配的某些部分的能力。 用於捕獲文本的默認正則表達式構造是一組括號。 更好的是,.Net regex使用(?<name>)
支持命名捕獲組 。
//using System.Text.RegularExpressions;
string pattern = @"(?<start>"
+ @"[A-Za-z]:\\[A-Za-z]+\\[A-Za-z]+\\[A-Za-z0-9]+\\[A-Za-z0-9]+\\[A-Za-z0-9._\s]+\\[A-Za-z]+\\[A-Za-z]+"
+ @")\\(?<next>[A-Za-z0-9._\s]+)(\\|$)";
string textToMatch = @"C:\FolderA\FolderB\FolderC\FolderD\Test 1.0\FolderE\FolderF\FinalFolder\Subfolder\Test.txt";
MatchCollection matches = Regex.Matches(textToMatch, pattern);
if (matches.Count > 0 ) {
var nextFolderName = matches[0].Groups["next"];
Console.WriteLine(nextFolderName);
}
正如在評論中發布的那樣,你的正則表達式似乎與整個字符串匹配。 但在這種特殊情況下,由於你正在處理文件名,我會使用FileInfo。
FileInfo fi = new FileInfo(textToMatch);
Console.WriteLine(fi.DirectoryName);
Console.WriteLine(fi.Directory.Name);
DirectoryName
將是完整路徑,而Directory.Name
將只是有問題的子文件夾。
那么,使用FileInfo
,這樣的事情呢?
(new FileInfo(textToMatch)).Directory.Parent.Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.