RegEx表示长度为0-2的字符串

时间:2021-05-21 21:37:20

I'm trying to match a string that can be either empty or have 1 or 2 numbers in it such as the following:

我正在尝试匹配一个字符串,该字符串可以为空或者包含1或2个数字,如下所示:

"" (empty) "1" "23"

“”(空)“1”“23”

String with more numbers or non-numeric characters should not match. My closest guess is the regex:

具有更多数字或非数字字符的字符串不应匹配。我最接近的猜测是正则表达式:

[0-9]{0,2}

[0-9] {0,2}

Which I read to say "the numbers 0 through 9 occurring 0 to 2 times." However, in practice I find that regex also matches longer strings like "333". How is it possible to restrict string length in regular expressions?

我读到的是“数字0到9出现0到2次”。但是,实际上我发现正则表达式也匹配更长的字符串,如“333”。如何在正则表达式中限制字符串长度?

3 个解决方案

#1


40  

Use the following regex:

使用以下正则表达式:

^[0-9]{0,2}$

You almost had it -- the ^ and $ characters are anchors that match the beginning and end of the string, respectively.

你几乎拥有它 - ^和$字符分别是匹配字符串开头和结尾的锚点。

For a more in-depth discussion on anchors, see here:

有关锚点的更深入讨论,请参见此处:

[Anchors] do not match any character at all. Instead, they match a position before, after or between characters. They can be used to "anchor" the regex match at a certain position.

[Anchors]根本不匹配任何角色。相反,它们匹配角色之前,之后或之间的位置。它们可用于在正确的位置“锚定”正则表达式匹配。

#2


7  

You need to anchor the regex:

你需要锚定正则表达式:

^[0-9]{0,2}$

Otherwise the regex will happily match substrings.

否则正则表达式将很乐意匹配子串。

#3


6  

Use the metacharacters for start and end of string:

使用元字符作为字符串的开头和结尾:

^[0-9]{0,2}$

If you don't use them, it matches anywhere in the string, and "12", which matches, is part of "123".

如果你不使用它们,它匹配字符串中的任何地方,匹配的“12”是“123”的一部分。

#1


40  

Use the following regex:

使用以下正则表达式:

^[0-9]{0,2}$

You almost had it -- the ^ and $ characters are anchors that match the beginning and end of the string, respectively.

你几乎拥有它 - ^和$字符分别是匹配字符串开头和结尾的锚点。

For a more in-depth discussion on anchors, see here:

有关锚点的更深入讨论,请参见此处:

[Anchors] do not match any character at all. Instead, they match a position before, after or between characters. They can be used to "anchor" the regex match at a certain position.

[Anchors]根本不匹配任何角色。相反,它们匹配角色之前,之后或之间的位置。它们可用于在正确的位置“锚定”正则表达式匹配。

#2


7  

You need to anchor the regex:

你需要锚定正则表达式:

^[0-9]{0,2}$

Otherwise the regex will happily match substrings.

否则正则表达式将很乐意匹配子串。

#3


6  

Use the metacharacters for start and end of string:

使用元字符作为字符串的开头和结尾:

^[0-9]{0,2}$

If you don't use them, it matches anywhere in the string, and "12", which matches, is part of "123".

如果你不使用它们,它匹配字符串中的任何地方,匹配的“12”是“123”的一部分。