正则表达式,用于处理类似“ test-12-1”的字符串(php)

时间:2018-12-21 23:58:05

标签: php regex preg-match

我需要编写正则表达式来解析此类输入字符串的帮助:

test-12-1

blabla12412-5

t-dsf-gsdg-x-10

前往下一场比赛:

test1

blabla124125

t-dsf-gsdg-x10

我尝试使用

之类的方法来达到此目的
$matches = [];
preg_match('/^[a-zA-Z0-9]+(-\d+)+$/', 'test-12-1', $matches);

但是我收到了意外的结果:

 array (
   0 => 'test-12-1',
   1 => '-1',
 )

您可以在这个游乐场的帮助下前进:https://ru.functions-online.com/preg_match.html?command={"pattern":"/^[a-zA-Z0-9]+(-\d+)+$/","subject":"test-12-1"}

非常感谢!

1 个答案:

答案 0 :(得分:3)

您可以使用

'~^(.*?)(?:-(\d+))+$~'

请参见regex demo

详细信息

  • ^-字符串的开头
  • (.*?)-第1组:除换行符以外的任何零个或多个字符,并且尽可能少
  • (?:-(\d+))+-出现1次或以上
    • --连字符
    • (\d+)-第2组:一个或多个数字(最后一次出现在组值中,因为它位于重复的非捕获组中)
  • $-字符串的结尾。

enter image description here