Richard
Richard

Reputation: 61419

Regular expression matches both numbers and units

I have some input, which includes lines like:

5feet
23m^2
7 m/s

I'd like to rewrite these as:

5 feet
23 m^2
7 m/s

And for that I could use:

re.sub(r"([0-9])(?=[a-zA-Z])",r"\1*","5feet")

However, I also have numbers which look like:

23e-7
58.234e-200

which are matched by the above pattern.

Is there a way to have the regular expression somehow match the first group, but exclude the second?

Upvotes: 0

Views: 473

Answers (1)

ruakh
ruakh

Reputation: 183484

You can tack on a negative lookahead assertion (?!...) (the opposite of (?=...)) to exclude that case:

re.sub(r"([0-9])(?=[a-zA-Z])(?!e[+-]?\d)",r"\1*","5feet")

Upvotes: 1

Related Questions