Wednesday, 24 October 2018

Insert space between specific characters but not if followed by specific characters regex

Using python regex, I wish to insert a space between alpha characters and numerals (alpha will always preceed numeral), but not between (numerals and hyphens) or between (numerals and underscores).

Ideally, I'd like it to replace all such examples on the line (see the 3rd sample string, below), but even just doing the first one is great.

I've gotten this far:

import re
item = "Bob Ro1-1 Fred"
txt = re.sub(r"(.*)(\d)", r"\1 \2", item)
print(txt) #prints Bob Ro1 -1 Fred (DESIRED WOULD BE Bob Ro 1-1 Fred)

I've tried sticking a ? in various places to ungreedify the search, but haven't yet found the magic.

Sample strings: Original ==> Desired output
1. "Bob Ro1 Sam cl3" ==> "Bob Ro 1 Sam cl 3"
2. "Some Guy ro1-1 Sam" ==> "Some Guy ro 1-1 Sam"
3. "ribbet ribbit ro3_2 bob wow cl1-3" ==> "ribbit ribbit ro 3_2 bow wow cl 1-3"



from Insert space between specific characters but not if followed by specific characters regex

No comments:

Post a Comment