我正在尝试匹配包含 1 到 3 位数字的字符串,
例子:
1
2
123
3
这是我试过的,
[\s]?[0-9]{1,3}[\s]?
这是匹配的,
123 ->a space after 123
你的问题不清楚,但似乎你正在寻找一个字符串
在这种情况下,正则表达式是^(?=.*\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
这应该适合你
^\\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)
匹配最多 3 位数字、任意数量的前导空格且没有尾随空格的模式将是:^\s*\d{1,3}$
.
这将匹配:
1
2
123
3
但不会匹配“123”,末尾有一个空格。
你能在你的正则表达式引擎中使用单词边界元字符吗?试试这个:\b\d{1,3}\b