1

我正在构建的应用程序的一部分允许您bash在交互式终端中评估命令。输入时,命令运行。我试图让它更灵活一点,并允许跨越多行的命令。

我已经检查了尾随反斜杠,现在我试图弄清楚如何判断是否有一个打开的字符串。我没有成功为此编写正则表达式,因为它也应该支持转义引号。

例如:

echo "this is a 
\"very\" cool quote"
4

1 回答 1

2

如果您想要一个匹配字符串 ( 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.
于 2013-03-22T11:48:38.937 回答