使用可选子字符串分割字符串

时间:2019-06-11 18:19:57

标签: python regex python-3.x python-3.6

这里,_also是可选的,如何将字符串_also拆分为可选?

>>> aa="may_be_this.is_the_string"
>>> aa.split('this.')[1]
'is_the_string'
>>>
>>> aa="may_be_this_also.is_the_string"
>>> aa.split('this[_also]*.')[1] # something like this, to make _also as optional substring.

3 个答案:

答案 0 :(得分:2)

这样的常规拆分正则表达式

this(?:_also)*\.

具有必需的this
其次是许多反对_also
后跟文字点.

没有捕获任何内容,因此此信息被排除为元素。

答案 1 :(得分:1)

您正在查看re.split

/ngx

答案 2 :(得分:0)

您可以使用正则表达式进行分割:

您应该在模式中屏蔽文字'.',否则'.'代表任何内容。如果您将(?:....)(== 0或1次出现)归为可选模式,则可以使用非分组?添加可选模式:

import re

aa = "may_be_this.is_the_string"
print(re.split(r'this\.',aa))           # 'this' and literal '.'

bb = "may_be_this_also.is_the_string"
print(re.split(r'this(?:_also)?\.',bb)) # 'this' and optional '_also' and literal '.'

输出:

['may_be_', 'is_the_string']
['may_be_', 'is_the_string']

使用'[_also]*'允许[。]内部所有字符出现0..n-可能不是您想要的。

使用原始字符串是获取指定正则表达式模式的好习惯。

您可能想读regex-info-内容很多,但涵盖了基础知识。为了测试正则表达式,我也想认可http://www.regex101.com-它具有python方言,并以明文形式解释正则表达式。

相关问题