且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中使用带有可选字符的正则表达式?

更新时间:2023-01-17 08:35:33

您可以在一组字符后放置一个 ? 以使其可选.

You can put a ? after a group of characters to make it optional.

您想要一个点后跟任意数量的数字 \.\d+,组合在一起 (\.\d+),可选 (\.\d+)?.坚持你的模式:

You want a dot followed by any number of digits \.\d+, grouped together (\.\d+), optionally (\.\d+)?. Stick that in your pattern:

import re
print re.match("(\d+(\.\d+)?)", "3434.35353").group(1)

3434.35353

print re.match("(\d+(\.\d+)?)", "3434").group(1)

3434