在行开头匹配\ d或\ d \ d

时间:2012-05-26 06:25:33

标签: regex

我正在尝试匹配这些行的开头以获取数字

1 - blah
01 - blah

我希望

1
01

我有这个正则表达式,但不明白为什么第二部分不匹配01

((^\d)|(^\d\d))

谢谢

1 个答案:

答案 0 :(得分:1)

您的模式与^的错误放置不匹配。

    除非您使用^或其他Mode modifier,否则
  • options会匹配字符串的开头。

试试这个

(?im)^(\d+)\b

<强>解释

<!--
(?im)^(\d+)\b

Match the remainder of the regex with the options: case insensitive (i); ^ and $ match at line breaks (m) «(?im)»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below and capture its match into backreference number 1 «(\d+)»
   Match a single digit 0..9 «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at a word boundary «\b»
-->