-2

我正在尝试匹配包含 1 到 3 位数字的字符串,

例子:

1
 2
123
  3

这是我试过的,

[\s]?[0-9]{1,3}[\s]?

这是匹配的,

123 ->a space after 123
4

4 回答 4

2

你的问题不清楚,但似乎你正在寻找一个字符串

  • 正好是 3 个字符长
  • 仅包含数字或空格
  • 至少包含一位数字

在这种情况下,正则表达式是^(?=.*\d)[\d\s]{3}$. 作为 Java 字符串:"^(?=.*\\d)[\\d\\s]{3}$".

解释:

^         # Start of string
(?=.*\d)  # Assert that there is at least one digit in the string
[\d\s]{3} # Match 3 digits or whitespace characters
$         # End of string
于 2012-08-05T20:20:24.703 回答
1

这应该适合你

^\\d{1,3}$.

解释

"^" +     // Assert position at the beginning of the string
"\\d" +    // Match a single digit 0..9
"{1,3}" +   // Between one and 3 times, as many times as possible, giving back as needed (greedy)
"$"       // Assert position at the end of the string (or before the line break at the end of the string, if any)
于 2012-08-05T19:59:46.030 回答
0

匹配最多 3 位数字、任意数量的前导空格且没有尾随空格的模式将是:^\s*\d{1,3}$.

这将匹配:

1
 2
123
  3

但不会匹配“123”,末尾有一个空格。

于 2012-08-05T20:06:24.950 回答
0

你能在你的正则表达式引擎中使用单词边界元字符吗?试试这个:\b\d{1,3}\b

于 2012-08-05T19:58:19.247 回答