Java Regex of String starts with a number and a fixed length

I made a regular expression to check the length of the string, all characters are numbers and begin with a number, for example 123 Next is my expression

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

But he could not check the length of the string. It only checks these lines for length 9 and starts at 123. But if I pass String 1234567891, it also checks for it. But how should I do this, which is not so on my side.

+3
source share
3 answers

As already answered here, the easiest way is to simply remove + :

 ^123\\d{9}$ 

or

 ^123\\d{6}$ 

Depending on what you need for sure.

You can also use a different, more complex and general approach, a negative look:

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

Explanation:

This: (?!.{10,}) is a negative forward look ( ?= Will be a positive forward look), this means that if the expression after waiting matches this pattern, then the general line does not match. Roughly this means: the criteria for this regular expression are satisfied only if the template in the negative appearance does not match.

In this case, a string matches only if .{10} does not match, which means 10 or more characters, so it matches only a pattern match of up to 9 characters.

A positive forecast ahead does the opposite, only a coincidence if the criteria in the forecast also coincide.

Just putting it here for the sake of curiosity, it is more complex than what you need for this.

+5
source

Try using this:

 ^123\\d{6}$ 

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

In addition, I deleted + . In this case, it will correspond to 1 or more \d (therefore an infinite number of digits).

+5
source

Based on your comment below Doorknobs answer you can do this:

 int length = 9; String prefix = "123"; // or whatever String regex = "^" + prefix + "\\d{ " + (length - prefix.length()) + "}$"; if (input.matches(regex)) { // good } else { // bad } 
0
source

Source: https://habr.com/ru/post/1241585/


All Articles