0

I have a following string pattern in Python language for variable name msg:

from:\t[xxxxxx]\n
message:\tcontent_1\n
created_time:\tyyyyy\n
from:\t[xxxxxx]\n
message:\tcontent_2\n
created_time:\tyyyyy\n
from:\t[xxxxxx]\n
message:\tcontent_3\n
created_time:\tyyyyy\n
        .
        .
        .
from:\t[xxxxxx]\n
message:\tcontent_n\n
created_time:\tyyyyy\n

What I am looking for matching is the content_1, content_2, content_3, ..., content_n To replace any "\n" inside any content_i with ","

For example of some content_i

sentence1\n sentence2\n sentence3

expected result as:

sentence1, sentence2, sentence3

but I found the problem when I try with

msg = re.sub(r"(\]\nmessage:.*?)\n", r"\1,", msg, re.M)

Some group of pattern, it also replace the \n between content_i and created_time with "," also but I don't want to replace it.

My question, I would like to use re module to searching \n in every content_i and replacing with "," only.

Note: any content_i can have many of \n inside

Sakares
  • 596
  • 12
  • 31

3 Answers3

1
import re
pattern = re.compile(r"(?<=message:\t).*?(?=\ncreated_time:)", re.DOTALL)
print map(lambda x:x.replace("\n", ","), pattern.findall(data))
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
1

Based off your data you can use the following to accomplish this.

>>> import re
>>> def f_breaks(match):
...     return match.group().replace('\n', ',')
...
>>> msg = 'YOUR STRING DATA'
>>> re.sub(r'(?si)(?<=message:\t).*?(?=\ncreated_time:)', f_breaks, msg)

See Working demo

hwnd
  • 67,942
  • 4
  • 86
  • 123
0

You can try this:

#!/usr/bin/python

import re

msg = r'''
from:\t[xxxxxx]\n
message:\tsentence1\nsententce2\nsentence3\nsentence4\n
created_time:\tyyyyy\n
from:\t[xxxxxx]\n
message:\tsentence1\nsententce2\nsentence3\n
created_time:\tyyyyy\n
'''

print re.sub(r'(?s)(?<=]\\n\nmessage:\\t).*?(?=\\n\ncreated_time:)',
    lambda m: m.group(0).replace(r'\n', ','), msg)
Casimir et Hippolyte
  • 85,718
  • 5
  • 90
  • 121