我正在构建的应用程序的一部分允许您在交互式终端中评估bash
命令。在输入时,运行该命令。我试图让它更灵活,并允许命令跨越多行。
我已经检查了一个尾随反斜杠,现在我正试图弄清楚如何判断是否有一个打开的字符串。我没有成功为此编写正则表达式,因为它也应该支持转义引号。
例如:
echo "this is a
\"very\" cool quote"
答案 0 :(得分: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.