Sakares
Sakares

Reputation: 606

regex matching and replacing with the pattern

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

Upvotes: 0

Views: 163

Answers (3)

hwnd
hwnd

Reputation: 70722

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

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

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)

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239443

import re
pattern = re.compile(r"(?<=message:\t).*?(?=\ncreated_time:)", re.DOTALL)
print map(lambda x:x.replace("\n", ","), pattern.findall(data))

Upvotes: 1

Related Questions