gpt4 book ai didi

Python 正则表达式匹配文字星号

转载 作者:太空狗 更新时间:2023-10-29 17:25:38 25 4
gpt4 key购买 nike

给定以下字符串:

s = 'abcdefg*'

如何匹配它或任何其他仅由小写字母组成且可选以星号结尾的字符串?我认为以下方法会起作用,但它不起作用:

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

它给出 None 而不是匹配对象。

最佳答案

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. $ 匹配字符串的结尾。

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

关于Python 正则表达式匹配文字星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9142736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com