Regex pattern to match a string ends with multiple charachters

934 Views Asked by At

I want to match a pattern that starts with $ and ends with either dot(.) or double quote("). I tried with this

re.findall(r"\$(.+?)\.",query1) 

Above works for starting with $ and ending with . How to add OR in ending characters so that it matches with pattern ending either with . or with "

Any suggestions ?

2

There are 2 best solutions below

0
On BEST ANSWER

The regex pattern you want is:

\$(.+?)[."]

Your updated script:

query1 = "The item cost $100.  It also is $not good\""
matches = re.findall(r"\$(.+?)[.\"]", query1)
print(matches)  # ['100', 'not good']
0
On

To match both a dot or double quote, you can use a character class [."]

As you want to exclude matching a single character in between, you can make use of a negated character class to exclude matching one of them [^".]

\$([^".]+)[."]

Regex demo

Example

import re

query1 = 'With a dollar sign $abc. or $123"'
print(re.findall(r'\$([^".]+)[."]', query1))

Output

['abc', '123']

Note: as the negated character class can also match newlines, you can exclude that using:

 \$([^".\n]+)[."]