如果之后没有找到数字,则正则表达式排除 dash/hyphen

regex exclude dash/hyphen if there no number found afterward

我尝试提取连字符之间的数字,它有效,但当找不到连字符后的数字并留下空格时,它会将连字符带入匹配项。

这是我尝试使用的代码:

$join = '';
if (preg_match('/(?<=book)[\s\d]+-?[\s\d]+/i', $find, $matches)) {
    if (strpos($matches[0], ' ') && strpos($matches[0], '-')) {
        $remove_whitespace = str_replace(' ', '', $matches[0]);
        $join.= 'b' . $remove_whitespace;
    }
    else {
        $remove_whitespace = str_replace(' ', '', $matches[0]);
        $join.= 'b' . $remove_whitespace;
    }
    echo $join;
}

我的预期:

  1. "Book 1 - abcd" = "Book 1"
  2. "Book 1 - " = "Book 1"
  3. "Book 1 - 2" = "Book 1-2"

实际输出:

  1. "Book 1 - abcd" = "Book 1-"(有连字符)
  2. "Book 1 - " = "Book 1-"(有连字符)
  3. "Book 1 - 2" = "Book 1-2"

您可以使用

'~Book\s*\K\d+(?:\s*-\s*\d+)?~'

regex demo

详情

  • Book - 文字字符串
  • \s* - 0+ 个空格
  • \K - 丢弃到目前为止匹配的文本的匹配重置运算符
  • \d+ - 1+ 位数
  • (?:\s*-\s*\d+)? - - 的可选序列,包含 0+ 个空格 (\s*-\s*),然后是 1+ 个数字。