regex 多符号分段

python自带的 i.e. text.split('.') 只能用单个符号给文本分段,如果想用多个符号分段呢? 比如想用句号,逗号,分号,感叹号问好等等标点,怎么办?
这时候用 re.split()

import re

a='Beautiful uef filenrfwe, is not really right; better*than\nugly'
print(re.split('(; |, |\*|\n)',a))

text = 'If you have a; suspicion about, an activity. but are !unsure if it ?warrants, escalation'
pattern = '(;|\.|,|\?|\!)'

new = re.split(pattern, text)


解释:

pattern = '(;|\.|,|\?|\!)'

| 代表 or
\ 是escape character, 由于 , ? ! 这些符号本身在regex中有特殊意味,所以要在前面加个escape,用\,, \?, \!来代表 逗号,问号,感叹号。
() 的效果是 split后仍然包括这些标点本身。 比较:

new = re.split('(;|\.|,|\?|\!)', text)

输出是:

['If you have a', ';', ' suspicion about', ',', ' an activity', '.', ' but are ', '!', 'unsure if it ', '?', 'warrants', ',', ' escalation']

然而:

  new = re.split(';|\.|,|\?|\!', text)

输出是:

['If you have a', ' suspicion about', ' an activity', ' but are ', 'unsure if it ', 'warrants', ' escalation']

你可能感兴趣的:(正则表达式,python)