Louis93
Louis93

Reputation: 3923

Regex: How do I exclude commas when in my pattern?

I want to find the first number that is sandwiched with commas on either end, and I came up with this:

m = re.search("\,([0-9])*\,",line)

However, this returns to me the number with the commas, how do I exclude them?

m.group(0) returns

',1620693,'

Upvotes: 1

Views: 752

Answers (2)

kfunk
kfunk

Reputation: 2082

group(0) will always return the entire match.

See python documentation:

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'

Upvotes: 7

Explosion Pills
Explosion Pills

Reputation: 191749

Use m.group(1). You also don't need to escape (backslash) the commas. m.group(0) refers to the entire match, and each number after that refers to matched groups.

Upvotes: 3

Related Questions