【问题标题】:PHP Regex to match the last occurrence of a stringPHP正则表达式匹配字符串的最后一次出现
【发布时间】:2012-11-17 01:43:21
【问题描述】:

我的字符串是$text1 = 'A373R12345'
我想找到这个字符串最后没有出现的数字。
所以我使用这个正则表达式^(.*)[^0-9]([^-]*)
然后我得到了这个结果:
1.A373
2.12345

但我的预期结果是:
1.A373R
(它有“R”)
2.12345

另一个例子是$text1 = 'A373R+12345'
然后我得到了这个结果:
1.A373R
2.12345

但我的预期结果是:
1.A373R+
(它有'+')
2.12345

我想包含最后一个无数字数字!!
请帮忙 !!谢谢!!

【问题讨论】:

    标签: php regex preg-match preg-split


    【解决方案1】:
    $text1 = 'A373R12345';
    preg_match('/^(.*[^\d])(\d+)$/', $text1, $match);
    echo $match[1]; // A373R
    echo $match[2]; // 12345
    
    $text1 = 'A373R+12345';
    preg_match('/^(.*[^\d])(\d+)$/', $text1, $match);
    echo $match[1]; // A373R+
    echo $match[2]; // 12345
    

    正则表达式分解的解释:

    ^ match from start of string
    (.*[^\d]) match any amount of characters where the last character is not a digit 
    (\d+)$ match any digit character until end of string
    

    【讨论】:

    • 它适用于我的情况!!谢谢!!你能为我解释一下正则表达式吗?我只知道。*[^\d] 的意思是你想找到最后一个没有数字的数字
    • @crypticツ你用的什么工具?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多