[英]How to write regular expression to get the substring from the string using regular expression in c#?
我有以下字符串
string s=@"\Users\Public\Roaming\Intel\Wireless\Settings";
我想要像這樣的輸出字符串
string output="Wireless";
子串什么,我想應該是經過“英特爾\\”,它應該與后“英特爾\\”字符串之前的第一個“\\”結尾Intel
之后Intel
字符串可能會有所不同。 我已經使用string.substring()實現了它,但是我想使用正則表達式來實現它嗎? 我應該寫什么正則表達式來獲取該字符串。
對於正則表達式解決方案,您可以使用:
(?<=intel\\)([^\\]+?)[\\$]
注意i
標志。
順便說一句,Split是比正則表達式更簡單,更快速的解決方案。 正則表達式與字符串模式相關聯。 對於靜態/固定的字符串結構,使用字符串函數操作它是一個明智的解決方案。
使用正則表達式,它將看起來像
var txt = @"\Users\Public\Roaming\Intel\Wireless\Settings";
var res = Regex.Match(txt, @"Intel\\([^\\]+)", RegexOptions.IgnoreCase).Groups[1].Value;
但是通常,您應該使用具有此類要求的字符串方法。 這是一個演示代碼(不檢查錯誤):
var strt = txt.IndexOf("Intel\\") + 6; // 6 is the length of "Intel\"
var end = txt.IndexOf("\\", strt + 1); // Look for the next "\"
var res2 = txt.Substring(strt, end - strt); // Get the substring
如果您希望在Intel /
/(?:intel\\)((\w+\\?)+)/gi
您將需要$1
結果。 請注意,如果字符串不包含Intel /或其后的任何內容,則$ 1將為空或不存在。
為什么不Path.GetDirectoryName
使用Path.GetDirectoryName
和Path.GetFileName
:
string s = @"\Users\Public\Roaming\Intel\Wireless\Settings";
string output = Path.GetFileName(Path.GetDirectoryName(s));
Debug.Assert(output == "Wireless");
可以遍歷目錄組件,直到找到單詞Intel
並返回下一個組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.