Java正则表达式匹配0-255的十进制数

Posted scruffybear

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java正则表达式匹配0-255的十进制数相关的知识,希望对你有一定的参考价值。

问题

需要在Java中匹配输入为0-255的十进制数,使用正则表达式解决。

解决

\\b(1?[0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b

解释如下:

"
\\b(1?[0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b
"
g
\\b assert position at a word boundary: (^\\w|\\w$|\\W\\w|\\w\\W)
1st Capturing Group (1?[0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])
1st Alternative 1?[0-9]{1,2}
1 matches the character 1 with index 4910 (3116 or 618) literally (case sensitive)
Match a single character present in the list below [0-9]
{1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
2nd Alternative 1[0-9][0-9]
1 matches the character 1 with index 4910 (3116 or 618) literally (case sensitive)
Match a single character present in the list below [0-9]
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
Match a single character present in the list below [0-9]
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
3rd Alternative 2[0-4][0-9]
2 matches the character 2 with index 5010 (3216 or 628) literally (case sensitive)
Match a single character present in the list below [0-4]
0-4 matches a single character in the range between 0 (index 48) and 4 (index 52) (case sensitive)
Match a single character present in the list below [0-9]
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
4th Alternative 25[0-5]
25 matches the characters 25 literally (case sensitive)
Match a single character present in the list below [0-5]
0-5 matches a single character in the range between 0 (index 48) and 5 (index 53) (case sensitive)
\\b assert position at a word boundary: (^\\w|\\w$|\\W\\w|\\w\\W)
Global pattern flags
g modifier: global. All matches (don't return after first match)
16-18	00

匹配例子如下:

00
01
99
255
100
150
175
200
250
0

参考

https://regex101.com/r/aAQ4bc/1

以上是关于Java正则表达式匹配0-255的十进制数的主要内容,如果未能解决你的问题,请参考以下文章

验证IP地址——正则表达式详解

使用 PCRE 正则表达式匹配两个二进制数的正确加法

如何用正则表达式检测ip是不是正确,求详解

python 正则RE匹配IP地址

正则表达式带逗号的十进制数

IP地址的正则表达式写法