python regex:只匹配一个字符实例的字符串

Chr*_*ris 9 python regex string

假设有两个字符串:

$1 off delicious ham.
$1 off delicious $5 ham.
Run Code Online (Sandbox Code Playgroud)

在Python中,如果字符串中只有一个$,我可以使用匹配的正则表达式吗?即,我希望RE匹配第一个短语,但不是第二个短语.我尝试过类似的东西:

re.search(r"\$[0-9]+.*!(\$)","$1 off delicious $5 ham.")
Run Code Online (Sandbox Code Playgroud)

..saying"匹配你看到$后跟任何东西除了另一个$." $$示例中没有匹配项,但$示例中也没有匹配项.

提前致谢!

简单的检查方法:

def test(r):
  s = ("$1 off $5 delicious ham","$1 off any delicious ham")    
  for x in s:
    print x
    print re.search(r,x,re.I)
    print ""
Run Code Online (Sandbox Code Playgroud)

Mat*_*ttH 11

>>> import re
>>> onedollar = re.compile(r'^[^\$]*\$[^\$]*$')
>>> onedollar.match('$1 off delicious ham.')
<_sre.SRE_Match object at 0x7fe253c9c4a8>
>>> onedollar.match('$1 off delicious $5 ham.')
>>>
Run Code Online (Sandbox Code Playgroud)

正则表达式的细分:
^字符串开头的锚点
[^\$]*零个或多个不$
\$匹配美元符号的
[^\$]*字符零个或多个不是$
$字符串末尾的锚点字符


Sil*_*ost 8

>>> '$1 off delicious $5 ham.'.count('$')
2
>>> '$1 off delicious ham.'.count('$')
1
Run Code Online (Sandbox Code Playgroud)

  • 我同意,正则表达式在这里会有点过分. (2认同)