[英]Regular expression for not splitting string if inside single or double quotes
我在C#中有一個帶有以下模式的正則表達式
Regex param = new Regex(@"^-|^/|=|:");
基本上,它用於命令行解析。
如果我通過下面的cmd線args,它也會傳遞給C:
/Data:SomeData /File:"C:\Somelocation"
如何使其不適用於雙引號或單引號內的字符?
您可以分兩步完成此操作:
使用第一個正則表達式
Regex args = new Regex("[/-](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
將字符串拆分為不同的參數。 然后使用正則表達式
Regex param = new Regex("[=:](?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
將每個參數拆分為參數/值對。
說明:
[=:] # Split on this regex...
(?= # ...only if the following matches afterwards:
(?: # The following group...
[^"]*" # any number of non-quote character, then one quote
[^"]*" # repeat, to ensure even number of quotes
)* # ...repeated any number of times, including zero,
[^"]* # followed by any number of non-quotes
$ # until the end of the string.
) # End of lookahead.
基本上,如果前面有偶數引號,它會在字符串中向前看。 如果有,我們就在一個字符串之外。 但是,這個(有些可管理的)正則表達式只處理雙引號,並且只有在那些內部沒有轉義引號的情況下。
以下正則表達式正確處理單引號和雙引號,包括轉義引號。 但我想你會同意,如果有人在生產代碼中找到這個,我保證有一篇關於The Daily WTF的專題文章:
Regex param = new Regex(
@"[=:]
(?= # Assert even number of (relevant) single quotes, looking ahead:
(?:
(?:\\.|""(?:\\.|[^""\\])*""|[^\\'""])*
'
(?:\\.|""(?:\\.|[^""'\\])*""|[^\\'])*
'
)*
(?:\\.|""(?:\\.|[^""\\])*""|[^\\'])*
$
)
(?= # Assert even number of (relevant) double quotes, looking ahead:
(?:
(?:\\.|'(?:\\.|[^'\\])*'|[^\\'""])*
""
(?:\\.|'(?:\\.|[^'""\\])*'|[^\\""])*
""
)*
(?:\\.|'(?:\\.|[^'\\])*'|[^\\""])*
$
)",
RegexOptions.IgnorePatternWhitespace);
在這里進一步解釋這個怪物。
您應該閱讀“ 掌握正則表達式 ”以了解為什么沒有針對您的問題的一般解決方案。 正則表達式無法處理任意深度。 一旦你開始逃脫逃脫角色或逃脫逃脫角色的逃脫或......你就迷失了。 您的用例需要解析器而不是正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.