Rohit Girdhar
Rohit Girdhar

Reputation: 353

Regex in Python (30 M)

I have the following text :

Adam, 30 M, Husband

Expected Output :

Adam, 30, M, Husband,

My Approach :

re.sub(r'\b(\d{1,2}\s\w{1},)\b', r'\1,', text)

How can I get a comma between 30 and M as shown in the output above?

Upvotes: 1

Views: 44

Answers (2)

jorge segovia tormo
jorge segovia tormo

Reputation: 1

You can use this expression:

([\S\d]+)[\,\s]+

and replace by: \1,

Upvotes: 0

akash karothiya
akash karothiya

Reputation: 5950

Try this:

>>> s = 'Adam, 30 M, Husband'
>>> re.sub(r'(?is)(\d+)(\s)', '\\1, ', s)
'Adam, 30, M, Husband'

Upvotes: 2

Related Questions