[英]Optimise the following regex
我需要一個正則表達式來匹配字符串,如下所示:
[
]
[
和]
之間包含任何字符(包括空格) [
和]
之間必須至少包含一個字符 ;
在]
。 跟隨;
允許所有字符(盡管無關緊要,因為我不在乎) ;
在出現]
之后,可以在]
和;
之間使用空格(閱讀制表符,空格-盡管我可以保證不會出現\\r\\n\\f\\v
,這就是我在下面使用\\s
原因) ;
。 如果;
在]
之后不存在,則]
必須在字符串的末尾。 我最后得到了通過所有初始測試的以下正則表達式: ^\\[([^]]+)](?:\\s+?;)?
。
速度是關鍵,因此,我希望改進正則表達式,以便在可能的情況下縮短一些周期。
我不太確定在這里使用lookahead是否有用。
編輯
例如:
[some;thing]
-有效,帶有捕獲組some;thing
[something]
-有效,帶有捕獲組的something
[something]
-無效,不是以[
[something] ;ojasodj
有效,捕獲something
[something]
-無效,在]
之后沒有空格;
當下
[something];
-有效,捕獲something
[]
-無效,必須在[
和]
之間至少包含一個字符
TL; DR: ^\\[([^]]+)](?:$|\\s*;)
^\\[([^]]+)]
已經是匹配正則表達式第一部分的最佳方法,除非您可以刪除捕獲組。 通過使用否定的字符類,可以避免在任何情況下都可能因任何類型的.*
或.*?
涉及的不必要的回溯.*?
圖案。
要滿足其他規則,您需要匹配字符串( $
)的末尾或可選空格和分號,因此應為(?:$|\\s*;)
。 我將$
放在第一位,因為這是較短的匹配項(因此可以更快地獲得成功),但這也取決於您的數據(如果第二種情況是絕大多數情況,則放在第一位)。
完整模式為^\\[([^]]+)](?:$|\\s*;)
請注意, $
后面可能有一個可選的\\n
,但是您的測試用例看起來不是多行的:)
試試這個模式^\\[[^\\]]+\\](?(?=\\s*;)\\s*;.*|$)
說明:
^\\[[^\\]]+\\]
將匹配字符串( ^
)開頭方括號中的文本(其中的至少一個字符,而不是]
)。
(?(?=\\s*;)\\s*;.*|$)
-如果將方括號括起來后僅是空格和分號,則將它們匹配,否則請確保其以字符串( $
)結尾。
這是您可以使用代碼代替的方法
public static bool IsValid(string str, out string capture)
{
capture = null;
// A null string is invalid
if(str == null) return false;
// An empty string is invalid
if(str.Length == 0) return false;
// A string that does not start with [ is invalid
if(str[0] != '[') return false;
int end = str.IndexOf(']');
// A string that does not have a ] is invalid
if(end == -1) return false;
// A string that does not have anything between the [ and ] is invalid
if(end == 1) return false;
// if the ] is not the end of the string we need to look for a ;.
if(end != str.Length -1)
{
bool semicolon = false
for(int i = end + 1; i < str.Length; i++)
{
// ; found so we can stop looking at characters.
if(str[i] == ';')
{
semicolon = true;
break;
}
// If non-whitespace is between the ] and ; the string is invalid
if(!char.IsWhiteSpace(str[i])) return false;
}
// No ; found so the string is invalid
if(!semicolon) return false;
}
// Capture the string between [ and ]
capture = str.Substring(1,end - 1);
return true;
}
顯然,它不如正則表達式短,但運行速度可能更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.