2013-03-22 80 views
1

我正在構建的應用程序的一部分允許您在交互式終端中評估bash命令。輸入時,該命令運行。我試圖讓它更靈活一些,並允許跨越多行的命令。檢查給定字符串中打開的未轉義引號

我已經檢查了一個尾隨的反斜槓,現在我試圖弄清楚如何判斷是否有一個打開的字符串。我還沒有成功地爲此編寫正則表達式,因爲它也應該支持逃脫的引號。

例如:

echo "this is a 
\"very\" cool quote" 
+0

到目前爲止您的RegEx是什麼?你在尋找'[\ s \ S] *'而不是'。*'? – 2013-03-22 11:38:52

回答

1

如果你想要一個字符串(subject)相匹配的正則表達式,只有當它不包含不平衡(轉義)報價,然後嘗試以下方法:

/^(?:[^"\\]|\\.|"(?:\\.|[^"\\])*")*$/.test(subject) 

說明:

^   # Match the start of the string. 
(?:  # Match either... 
[^"\\] # a character besides quotes or backslash 
|   # or 
\\.  # any escaped character 
|   # or 
"   # a closed string, i. e. one that starts with a quote, 
(?:  # followed by either 
    \\.  # an escaped character 
|   # or 
    [^"\\] # any other character except quote or backslash 
)*  # any number of times, 
"   # and a closing quote. 
)*   # Repeat as often as needed. 
$   # Match the end of the string.