Rob Young
Rob Young

Reputation: 1245

Non-consuming regular expression split in Python

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 more 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.

Upvotes: 13

Views: 3663

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

>>> 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 ?<=.

Upvotes: 11

eyquem
eyquem

Reputation: 27575

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!', ' :)']

Upvotes: 10

Related Questions