Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex of String start with number and fixed length

Tags:

java

regex

I made a regular expression for checking the length of String , all characters are numbers and start with number e.g 123 Following is my expression

REGEX =^123\\d+{9}$";

But it was unable to check the length of String. It validates those strings only their length is 9 and start with 123. But if I pass the String 1234567891 it also validates it. But how should I do it which thing is wrong on my side.

like image 801
waseem Avatar asked Dec 21 '22 09:12

waseem


2 Answers

Like already answered here, the simplest way is just removing the +:

^123\\d{9}$

or

^123\\d{6}$

Depending on what you need exactly.

You can also use another, a bit more complicated and generic approach, a negative lookahead:

(?!.{10,})^123\\d+$

Explanation:

This: (?!.{10,}) is a negative look-ahead (?= would be a positive look-ahead), it means that if the expression after the look-ahead matches this pattern, then the overall string doesn't match. Roughly it means: The criteria for this regular expression is only met if the pattern in the negative look-ahead doesn't match.

In this case, the string matches only if .{10} doesn't match, which means 10 or more characters, so it only matches if the pattern in front matches up to 9 characters.

A positive look-ahead does the opposite, only matching if the criteria in the look-ahead also matches.

Just putting this here for curiosity sake, it's more complex than what you need for this.

like image 148
pcalcao Avatar answered Jan 08 '23 12:01

pcalcao


Try using this one:

^123\\d{6}$

I changed it to 6 because 1, 2, and 3 should probably still count as digits.

Also, I removed the +. With it, it would match 1 or more \ds (therefore an infinite amount of digits).

like image 24
tckmn Avatar answered Jan 08 '23 14:01

tckmn