Ayesha Ameer
Ayesha Ameer

Reputation: 1

Regular Expression formatting

I have an input box and the condition is to allow the user to enter only numbers, the numbers entered should be in the following format in groups of 4, ex: 4444 5555 and the maximum number of characters to be entered in the textbox should be 9. I am pretty new to regex, so have no clue of how to start. A working sample in fiddle would be of great help.

Upvotes: 0

Views: 63

Answers (4)

Tanul
Tanul

Reputation: 354

As per example provided this regex will help

/^[0-9][0-9 ]*$/

This represent numbers with spaces in between. For eg. 444 444. But if you put in this way ' 444 444' like first inserting space then start the numbers then it wont allow.

For that you can use /^[0-9 ]*$/

^ represent start and $ represent end. So between start and end you can write numbers with spaces.

Upvotes: 0

LVBen
LVBen

Reputation: 2061

If you want 1 or more of something use '+'. For example 4+ would be 1 or more consecutive '4's.

Use * to for things that you want 0 or more of!

Use parentheses for groups of characters or groups of other groups.

If you want a space in between, then use the space character between two of them.

It looks like you want 1 or more '4's followed by 0 or more (space followed by 1 or more '4's)

This regular express would match all of the following strings: "4+( 4+)*"

44444

4 44 4

4 4 4

4

4444444444

4 4

44444444444444 44444444444444444 4444444444444444

4444 4444 44

Upvotes: 0

6502
6502

Reputation: 114579

If the length is fixed then you can just use \d to represent a digit

/^\d\d\d\d \d\d\d\d \d\d\d\d \d\d$/

or use the {n} multiplier instead

/^\d{4} \d{4} \d{4} \d\d$/

if instead the total length is arbitrary and you just want to be sure that every four digits you have a space things are just slightly more complex:

/^(\d{4} )*\d{1,4}$/

the meaning is that you want zero or more groups formed with 4 digits and one space followed by 1 to 4 digits. In the last part you can use {0,4} if you also want to accept an empty string as a valid response.

Upvotes: 1

Mutahhir
Mutahhir

Reputation: 3832

If the requirement is strictly 10 numbers in the above grouping with spaces in the middle, the regex is simple:

/^\d{4}\s\d{4}\s\d{2}$/

Where \d means that it would only match a numeric character, {4} means that it would look exactly 4 times for the previous match (\d), and in this case that would match 4 numeric characters. \s means one whitespace, and similarly like the {4}, \d{2} matches 2 numeric characters. The ^ and $ mean start of the string to be matched and end of the string to be matched respectively.

Hope this helps.

Upvotes: 1

Related Questions