特定模式之间的正则表达式

时间:2013-12-19 16:22:27

标签: regex regex-negation

我希望在特定模式中获取并替换字符串:$here is a string$应替换为$$$here is a string$$$。但是,$$$$here is text$$也可能会出现

我使用这个:\$.+?(\$)搜索模式,它可以很好地避免$$这些空的美元符号,但它仍然会找到:$$text$$它不应该。 (好吧,由于它的性质,它实际上找到$$text$,但那并不是真的更好)

我需要找到一种方法来禁止在最后$之后出现另一个$(可能使用正则表达式否定),但是如何?

提前致谢。

2 个答案:

答案 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}匹配nm

之间的模式

{n}完全匹配模式n

[^...]匹配与给定字符集

不匹配的所有字符