Pythonista
Pythonista

Reputation: 11625

alternative regex to match all text in between first two dashes

I'm trying to use the following regex \-(.*?)-|\-(.*?)* it seems to work fine on regexr but python says there's nothing to repeat?

I'm trying to match all text in between the first two dashes or if a second dash does not exist after the first all text from the first - onwards.

Also, the regex above includes the dashes, but would preferrably like to exclude these so I don't have to do an extra replace etc.

Upvotes: 1

Views: 2359

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use re.search with this pattern:

-([^-]*)

Note that - doesn't need to be escaped.

An other way consists to only search the positions of the two first dashes, and to extract the substring between these positions. Or you can use split:

>>> 'aaaaa-bbbbbb-ccccc-ddddd'.split('-')[1]
'bbbbbb'

Upvotes: 2

Related Questions