K Max
K Max

Reputation: 102

changing a word surrounded by numbers using re.sub

I want to change "to" to "-" only when it is surrounded by numbers or numbers and spaces e.g. 34to55 or 34 to 55 both to be changed to 34-55. Also, I don't want to change it when the word begins or ends with alphabets e.g. abc34to55def

I tried

re.sub(?<![a-z])(\d)to(\d)(?!\[a-z]), \\1-\\2, 34to55)

but it doesn't give me what I want.

Any help would be greatly appreciated

Upvotes: 1

Views: 58

Answers (1)

The fourth bird
The fourth bird

Reputation: 163642

You can use 2 capture groups with word boundaries and use the groups in the replacement.

\b(\d+)\s*to\s*(\d+)\b
  • \b A word boundary to prevent a partial match
  • (\d+) Capture group 1, match 1+ digits
  • \s*to\s* Match to between optional whitespace chars
  • (\d+) Capture group 2, match 1+ digits
  • \b A word boundary

and replace with

\1-\2

Regex demo | Python demo

import re
 
pattern = r"\b(\d+)\s*to\s*(\d+)\b"
s = ("34to55 or 34 to 55\n"
    "abc34to55def")
result = re.sub(pattern, r"\1-\2", s)
 
if result:
    print (result)

Result

34-55 or 34-55
abc34to55def

Upvotes: 4

Related Questions