我希望在特定模式中获取并替换字符串:$here is a string$
应替换为$$$here is a string$$$
。但是,$$
或$$here is text$$
也可能会出现不。
我使用这个:\$.+?(\$)
搜索模式,它可以很好地避免$$
这些空的美元符号,但它仍然会找到:$$text$$
它不应该。 (好吧,由于它的性质,它实际上找到$$text$
,但那并不是真的更好)
我需要找到一种方法来禁止在最后$
之后出现另一个$
(可能使用正则表达式否定),但是如何?
提前致谢。
答案 0 :(得分:4)
如果你有可用的外观:
(?<!\$)\$[^$]+\$(?!\$)
编辑:包括评论
(?<!\$) # Negative lookbehind. The character before this cannot
# be a $ (it can be the beginning of the string since
# this is a zero-width assertion
\$ # literal $
[^$] # Character class meaning "anything but a $"
+ # Match one or more of this character class
\$ # literal $
(?!\$) # Negative lookahead. Similar to the lookbehind, but
# this cannot be *followed* by $
答案 1 :(得分:0)
您正在选择美元符号后面的任何字符。相反,尝试做任何字符但美元符号。您还可以使用大括号将匹配数限制为1.
\$[^$]+?\${1}
{n,m}
匹配n
和m
次
{n}
完全匹配模式n
次
[^...]
匹配与给定字符集