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

Regexp for handling "test-12-1"-like strings (php)

我需要一些帮助来编写正则表达式来解析像这样的输入字符串:

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

非常感谢!

您可以使用

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

regex demo

详情

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