a regular expression that is a half-width number up to five digits and does not allow "0 only"

Asked 1 years ago, Updated 1 years ago, 62 views

Can such regular expressions be written?
Thank you for your cooperation.
0 → out
00→out
000→out
0000→out
00000→out

1 → ok
123→ok
0123→ok
00123→ok
12345 → ok

java regular-expression

2022-09-30 19:10

1 Answers

Why don't you use the negative read-ahead assertion (?!...) to exclude "only 0" first?I think negative look-ahead can be used in most processing systems.

^(?!0+$)\d{1,5}$

On Python, I tested the following and found everything.

import re

pattern=r'^(?!0+$)\d{1,5}$'
print(re.search(pattern, '0'))

For Java, the regular expression is the same.The look-ahead should be used in the same way in recent programming languages.

String str="0";
String pattern="^(?!0+$)\\d{1,5}$";
Pattern p = Pattern.compile(pattern);
Matcher m=p.matcher(str);
System.out.println(m.find());


2022-09-30 19:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.