John Ohara
John Ohara

Reputation: 2901

Regex fixed number of characters but any quantity of spaces

I'm validating some input fields. Here's the regex for a simple example:

^\[0-9]\{6,6}\$

In the example, it requires 6 numbers to be input. However, I want to relax the validation a little and allow spaces where necessary, and remove them later - an example might be a bank sort code.

In the UK, a sort code could be written as 123456, or perhaps 12 34 56.

I know I can amend the expression to include a space within the brackets and relax the numbers in the curly brackets, but what I'd like to do is continue to limit the digits so that 6 must always be input, and allow none or more spaces - of course the spaces could be anywhere.

I'm not sure how to approach this - any ideas, help appreciated.

Upvotes: 0

Views: 1243

Answers (3)

Kieran101
Kieran101

Reputation: 699

I think you want to look at a lookahead expression

This site explains them in more detail

For your example, ^(?=(\s*[0-9]\s*){6})(\d*\s*)$

This looks for any amount of space, followed by a digit followed by any amount of space 6 times.

Other answers I've seen so far only allow a total of 6 characters, this expression will allow any number of spaces but only 6 digits, no more, no less.

Note: ^(\s*[0-9]\s*){6}$ this will also work, without the lookahead expression

JavaScript Example

Upvotes: 1

Amit
Amit

Reputation: 46323

Try this:

^(\d\s*){6}$

It allows 0 or more whitespace characters after every digit.

If you want to limit whitespace to be inside the digits (without leading or trailing spaces):

^(\d\s*){5}\d$

Upvotes: 5

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

If you allow spaces at any position alongside 6 digits, then you need

^(\s*[0-9]){6}\s*$

See regex demo

The \s* matches any whitespace, 0 or more repetitions.

Note that a limiting quantifier {6,6} (minimum 6 and maximum 6 repetitions) is equal to {6}.

Also, note that you need to double escape the \s as \\s if you pass the regex pattern as a regular string literal.

And if you plan to only allow regular spaces, not all whitespace, just use

^([ ]*[0-9]){6}[ ]*$

Upvotes: 4

Related Questions