开发者

Non-consuming regular expression split in Python

开发者 https://www.devze.com 2023-03-01 04:02 出处:网络
How can a string be split on a separator expression while leaving that separator on the preceding string?

How can a string be split on a separator expression while leaving that separator on the preceding string?

>>> text = "This is an example. Is it made up of mor开发者_运维知识库e than once sentence? Yes, it is."
>>> re.split("[\.\?!] ", text)
['This is an example', 'Is it made up of more than one sentence', 'Yes, it is.']

I would like the result to be.

['This is an example.', 'Is it made up of more than one sentence?', 'Yes, it is.']

So far I have only tried a lookahead assertion but this fails to split at all.


>>> re.split("(?<=[\.\?!]) ", text)
['This is an example.', 'Is it made up of more than once sentence?', 'Yes, it is.']

The crucial thing is the use of a look-behind assertion with ?<=.


import re

text = "This is an example.A particular case.Made up of more "\
       "than once sentence?Yes, it is.But no blank !!!That's"\
       " a problem ????Yes.I think so! :)"


for x in re.split("(?<=[\.\?!]) ", text):
    print repr(x)

print '\n'

for x in re.findall("[^.?!]*[.?!]|[^.?!]+(?=\Z)",text):
    print repr(x)

result

"This is an example.A particular case.Made up of more than once sentence?Yes, it is.But no blank !!!That'sa problem ????Yes.I think so!"
':)'


'This is an example.'
'A particular case.'
'Made up of more than once sentence?'
'Yes, it is.'
'But no blank !'
'!'
'!'
"That's a problem ?"
'?'
'?'
'?'
'Yes.'
'I think so!'
' :)'

.

EDIT

Also

import re

text = "! This is an example.A particular case.Made up of more "\
       "than once sentence?Yes, it is.But no blank !!!That's"\
       " a problem ????Yes.I think so! :)"

res = re.split('([.?!])',text)

print [ ''.join(res[i:i+2]) for i in xrange(0,len(res),2) ]

gives

['!', ' This is an example.', 'A particular case.', 'Made up of more than once sentence?', 'Yes, it is.', 'But no blank !', '!', '!', "That's a problem ?", '?', '?', '?', 'Yes.', 'I think so!', ' :)']
0

精彩评论

暂无评论...
验证码 换一张
取 消