nedla2004
nedla2004

Reputation: 1145

Regex Change Space Separated Items To Comma Separated Items

I have this regex to change a list that is separated by spaces to a list separated by commas, re.sub(r'(\w+)', r'\1,', text), but I need it to only match if the line starts with xyz, like this:

xyz a bcd ef --> xyz a,bcd,ef

But should not change any thing for a line that does not start with xyz, like this:

xy abc def #Nothing changes 

This xyz .*(\w+) does not work, because it only matches the xyz a bcd and does not separate the a and the bcd.

Upvotes: 0

Views: 52

Answers (1)

Navidad20
Navidad20

Reputation: 832

What about something like this:

if re.match(r'xyz', text):
    line = text.partition('xyz ')
    text = line[1] + line[2].replace(' ', ',')

Upvotes: 2

Related Questions