【问题标题】:Regex match string that ends with number以数字结尾的正则表达式匹配字符串
【发布时间】:2015-08-01 09:27:51
【问题描述】:

什么是正则表达式来匹配以数字结尾的字符串,例如

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

试过了,还是不行

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

再次感谢,

开头的字符串也需要具体

【问题讨论】:

  • 你使用什么语言?
  • 我正在使用 PHP preg_match

标签: php regex preg-match regex-negation


【解决方案1】:

随便用

\d$

检查你的字符串是否以数字结尾

如果您希望字符串是“c”后跟一些数字,请使用

c\d+$

【讨论】:

  • @u 什么?你是如何测试的?
  • @user2217084:它适用于任何以数字结尾的字符串。你试过了吗?
  • 正则表达式 c\d$
  • 开头的字符串也需要具体
  • @user2217084 注意d后面的+
【解决方案2】:

你可以使用这个正则表达式模式

^c[0-9]+$

【讨论】:

  • 这是关于 PHP 而不是 Java。
  • 对不起,我一开始忘了看评论,我只是看了这个问题。我只是想为提问者找到正确的模式。对不起。
【解决方案3】:

要匹配任何以数字结尾的字符串,请使用:[\s\S]*\d$

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

【讨论】:

    【解决方案4】:
    "(c|C).*[0-9]$"
    

    查看工作示例:https://regex101.com/r/4Q2chL/3

    【讨论】:

    • 这是匹配c;,:.?!$+0
    【解决方案5】:

    动态方式是:

    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")
    

    结果:

    c1234 -match
    c12 -match
    c - nomatch
    

    【讨论】:

    • 这是一个 PHP 问题,而不是 Python。
    • ops,因为问题中没有提到,所以给出了我自己的建议:)
    • 提到了,看标签。
    猜你喜欢
    • 2021-01-17
    • 2016-03-26
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2016-12-07
    相关资源
    最近更新 更多