Python regex match literal asterisk

别说谁变了你拦得住时间么 提交于 2021-02-16 04:25:40

问题


Given the following string:

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)

It gives None and not a match object.


回答1:


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

The following will do it:

re.match(r"^[a-z]+[*]?$", s)
  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.




回答2:


\*? means 0-or-1 asterisk:

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



回答3:


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

The [a-z]+ matches the sequence of lowercase letters, and \*? matches an optional literal * chatacter.




回答4:


Try

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

this means "a string consisting zero or more lowercase characters (hence the first asterisk), followed by zero or one asterisk (the question mark after the escaped asterisk).

Your regex means "exactly one lowercase character followed by one or more asterisks".




回答5:


You forgot the + after the [a-z] match to indicate you want 1 or more of them as well (right now it's matching just one).

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


来源:https://stackoverflow.com/questions/9142736/python-regex-match-literal-asterisk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!