本文介绍了Python正则表达式匹配文字星号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下字符串:
s = 'abcdefg*'
如何匹配它或任何其他仅由小写字母组成且可选以星号结尾的字符串?我认为以下方法可行,但它不起作用:
How can I match it or any other string only made of lowercase letters and optionally ending with an asterisk? I thought the following would work, but it does not:
re.match(r"^[a-z]\*+$", s)
它给出 None
而不是匹配对象.
It gives None
and not a match object.
推荐答案
以下将做到这一点:
re.match(r"^[a-z]+[*]?$", s)
^
匹配字符串的开头.[a-z]+
匹配一个或多个小写字母.[*]?
匹配零个或一个星号.$
匹配字符串的结尾.
- The
^
matches the start of the string. - The
[a-z]+
matches one or more lowercase letters. - The
[*]?
matches zero or one asterisks. - The
$
matches the end of the string.
您的原始正则表达式恰好匹配一个小写字符后跟一个或多个星号.
Your original regex matches exactly one lowercase character followed by one or more asterisks.
这篇关于Python正则表达式匹配文字星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!