我有三种可能的形式将通过正则表达式,我想匹配它们。
text1
text1 text2
text1 text2 ;text3
到目前为止,我已经(.*?)(?:\s)(.*)
为 'text1 text2'
工作,但我能够处理如果存在分号,则所有三种情况。有什么想法吗?
最佳答案
下面应该可以工作,它还会将“text1”、“text2”和“text3”放入正确的组中:
^(.+?)(?:\s(.*?)(?:\s;(.*))?)?$
查看它的工作情况:http://www.rubular.com/r/IyPyF3wXLx
解释如下:
^ # start of string
(.+?) # put text1 in group 1
(?: # start an optional non-capturing group
\s(.*?) # space followed by text2, put text2 in group 2
(?: # start an optional non-capturing group
\s;(.*) # space and semicolon, followed by text3, put text3 in group 3
)? # end of optional non-capturing group
)? # end of optional non-capturing group
$ # end of string
中间的可选组允许您的正则表达式匹配 text2 和 text3(如果它们存在),但如果它们不存在则仍然匹配。
关于python - python 中的正则表达式,在字符串中具有可选文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9384995/