Regex match string that ends with number

孤者浪人 提交于 2019-12-12 03:37:15

问题


What is a regex to match a string that ends with a number for example

"c1234" - match
"c12" - match
"c" - no match

Tried this but it doesn't work

(?|c(?|[0-9]*$))

Thanks again,

The beggining string needs to be specific too


回答1:


Just use

\d$

to check your string ends with a digit

If you want your string to be a "c" followed by some digits, use

c\d+$



回答2:


To match any string ending with a digit use: [\s\S]*\d$

if (preg_match('/[\s\S]*\d$/', $value)) {
   #match
} else {
  #no match
}



回答3:


You can use this regular expression pattern

^c[0-9]+$



回答4:


"(c|C).*[0-9]$"

See working example: https://regex101.com/r/4Q2chL/3




回答5:


dynamic way would be:

import re
word_list = ["c1234", "c12" ,"c"]
for word in word_list:
    m = re.search(r'.*\d+',word)
    if m is not None:
        print(m.group(),"-match")
    else:
        print(word[-1], "- nomatch")

RESULT:

c1234 -match
c12 -match
c - nomatch


来源:https://stackoverflow.com/questions/30344483/regex-match-string-that-ends-with-number

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