Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex: match a string with only one instance of a character

Suppose there are two strings:

$1 off delicious ham.
$1 off delicious $5 ham.

In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried something like:

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

..saying "Match where you see a $ followed by anything EXCEPT for another $." There was no match on the $$ example, but there was also no match on the $ example.

Thanks in advance!

Simple test method for checking:

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 ""
like image 728
Chris Avatar asked Jul 02 '10 14:07

Chris


2 Answers

>>> 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.')
>>>

Breakdown of regexp:
^ Anchor at start of string
[^\$]* Zero or more characters that are not $
\$ Match a dollar sign
[^\$]* Zero or more characters that are not $
$ Anchor at end of string

like image 157
MattH Avatar answered Oct 04 '22 05:10

MattH


>>> '$1 off delicious $5 ham.'.count('$')
2
>>> '$1 off delicious ham.'.count('$')
1
like image 35
SilentGhost Avatar answered Oct 04 '22 03:10

SilentGhost