如何在python中使用带有可选字符的正则表达式? [英] How to use regex with optional characters in python?
问题描述
说我有一个字符串
"3434.35353"
和另一个字符串
"3593"
如果另一个失败,我如何制作一个能够匹配两者的单个正则表达式,而不必将模式设置为其他模式?我知道 \d+
会匹配 3593
,但它不会对 3434.35353
做任何事情,但是 (\d+\.\d+
) 只会匹配带有小数的那个,并且不会返回 3593
的匹配项.
How do I make a single regular expression that is able to match both without me having to set the pattern to something else if the other fails? I know \d+
would match the 3593
, but it would not do anything for the 3434.35353
, but (\d+\.\d+
) would only match the one with the decimal and return no matches found for the 3593
.
我希望 m.group(1)
返回:
"3434.35353"
或
"3593"
推荐答案
您可以在一组字符后放置一个 ?
以使其可选.
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
这篇关于如何在python中使用带有可选字符的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!