【问题标题】:mysql REGEXP to match a string ending in 2 digits that are preceded only by non-digitsmysql REGEXP 匹配以 2 位数字结尾且仅以非数字开头的字符串
【发布时间】:2015-05-04 15:37:05
【问题描述】:

我在这方面遇到了很多困难。

在 MySQL 中,我想查询以两位数结尾的字符串的列。我不在乎前面还有什么,只要最后一个字符是两个数字前面至少有一个非数字

例如,这些字符串应该匹配:

"Nov. 12th, 60"

"34 Bar 56"

"Foo-BAR-01"

"33-44-55"

"-------88"

"99"

当我这样做时:

SELECT <string> REGEXP <pattern>

现在,&lt;pattern&gt; 位是我需要帮助的地方。

谢谢。

【问题讨论】:

    标签: mysql sql regex select


    【解决方案1】:
    SELECT * FROM mytable WHERE mycolumn REGEXP "^.*[^0-9][0-9]{2}$";
    

    正则表达式解释:

    ^.*[^0-9][0-9]{2}$
    
    Assert position at the beginning of the string «^»
    Match any single character that is NOT a line break character «.*»
       Between zero and unlimited times, as few or as many times as needed to find the longest match in combination with the other quantifiers or alternatives «*»
    Match any single character that is NOT present in the list below and that is NOT a line break character «[^0-9]»
       A character in the range between “0” and “9” «0-9»
    Match a single character in the range between “0” and “9” «[0-9]{2}»
       Exactly 2 times «{2}»
    Assert position at the very end of the string «$»
    

    【讨论】:

    • 谢谢你,佩德罗。感谢您抽出这么多时间来回答我的问题。
    • 好吧,在您进行编辑后,请注意:"^.*[[:&lt;:]][^0-9]?[0-9]{2}[[:&gt;:]]$" 已损坏!是的,您最初的回答与我的 99 不匹配,但我愿意忽略,因为该特定字符串是一种边缘情况,不太可能出现在我的数据中。
    • 尽管如此,本着学术精神,看看如何为99 带来案例。干杯。
    【解决方案2】:

    字符串不用全部描述,结尾就够了:

    SELECT 'Nov. 12th, 60' REGEXP '(^|[^[:digit:]])[[:digit:]]{2}$';
    SELECT '99' REGEXP '(^|[^[:digit:]])[[:digit:]]{2}$'
    

    简而言之,[[:digit:]]{2}$ 末尾的两位数字前面是一个非数字字符 [^[:digit:]],或 | 字符串的开头 ^

    注意:你可以用更少的posix风格来写它,它不会改变任何东西(只是更短一点):

    SELECT 'Nov. 12th, 60' REGEXP '(^|[^0-9])[0-9]{2}$';
    

    【讨论】:

    • 谢谢@Casmir。你的模式确实适合我的情况。但是让我正式接受第一个答案。顺便说一下,那些 POSIX 样式虽然更冗长,但实际上可能更“令人难忘”。
    猜你喜欢
    • 2012-09-13
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2016-12-07
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多