您的将无法正确匹配字符串x$
。如果要匹配整个字符串,请尝试
"""^\$$|^[^\$].*$|^\$[^i\{].*$"""
我们匹配由 分隔的三个序列中的任何一个|
:
^\$$
^[^\$]+.*$
^\$[^i\{]+.*$
让我们把它分开:
// First pattern--match lone '$' character
^ // Matches start of string
\$ // Matches the literal character '$'
$ // Matches end of string
// Second pattern--match a string starting with a character other than '$'
^ // Start of string
[^\$]+ // Match at least one non-'$':
+ // Match one or more
[^ ] // ...of characters NOT listed...
\$ // ...namely, a literal '$'
.* // Any number of other characters
$ // End of the string
// Third pattern--match a string starting with '$' but not '$i' or '${'
^ // Start of string
\$ // The literal character '$'
[^i\{]+ // Match at least one non-'i'/non-'{'
.* // Any number of other characters
$ // End of the string
如果您不匹配整个字符串,则必须担心诸如foo$image{Hi}
. 如果您还想匹配空字符串,^$|
请在匹配之前添加。
请注意,这是专门为使用正则表达式而编写的,而不是考虑到您的解析器组合器。根据您拥有的其他规则,您可能想要也可能不想匹配整个字符串。