Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex - How to read numbers only 5 to 7 digits

Tags:

java

regex

I have following now.

regex=^[0-9]{6}$

this is working for starting 0 to 9 and for 6 and 7 digit number.

Please suggest how can i add for 5, 6 and 7 digit numbers.

like image 362
Space Avatar asked Jun 13 '11 14:06

Space


People also ask

How does RegEx Match 5 digits?

match(/(\d{5})/g);

How do you specify a number range in RegEx?

\d for single or multiple digit numbers It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range. [1-9][0-9] will match double digit number from 10 to 99.

What is the regular expression for numbers only in Java?

regex = "[0-9]+"; Match the given string with Regular Expression. In Java, this can be done by using Pattern.

Can you use RegEx for numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.


1 Answers

use the range form of the { } operator

^[0-9]{5,7}$

Range inside of {N,M} is demarcated with a comma and translates into a string with length between N and M inclusive.

This is notably different from the [ ] operator which is to describe a character group and uses the - symbol to demarcate its ranges.

like image 190
zellio Avatar answered Sep 23 '22 02:09

zellio