nedla2004 nedla2004 - 8 days ago 4
Python Question

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
.

Answer

What about something like this:

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