Python正则表达式匹配文字星号 [英] Python regex match literal asterisk

查看:142
本文介绍了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.

推荐答案

如何匹配它或任何其他仅由小写字母组成并可选以星号结尾的字符串?

How can I match it or any other string only made of lowercase letters and optionally ending with an asterisk?

以下将做到这一点:

re.match(r"^[a-z]+[*]?$", s)

  1. ^ 匹配字符串的开头.
  2. [a-z]+ 匹配一个或多个小写字母.
  3. [*]? 匹配零个或一个星号.
  4. $ 匹配字符串的结尾.
  1. The ^ matches the start of the string.
  2. The [a-z]+ matches one or more lowercase letters.
  3. The [*]? matches zero or one asterisks.
  4. The $ matches the end of the string.

您的原始正则表达式恰好匹配一个小写字符后跟一个或多个星号.

Your original regex matches exactly one lowercase character followed by one or more asterisks.

这篇关于Python正则表达式匹配文字星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆