Regular expression to match a group of alphanumeric characters followed by a group of spaces with a fixed number of characters

I am trying to write a regex using C # /. Net, which matches 1-4 letter characters, followed by spaces, followed by 10 digits. Trap is the number of spaces plus the number of alphanumeric characters should be 4, and the spaces should follow the alphanumeric characters, and not be marked.

I have a complete loss on how to do this. I can do ^[A-Za-z\d\s]{1,4}[\d]{10}$ , but this allows you to skip spaces somewhere in the first four characters. Or I could do ^[A-Za-z\d]{1,4}[\s]{0,3}[\d]{10}$ to save space together, but that would allow more than just four characters before the 10-digit number.

Valid: A12B1234567890 AB1 1234567890 AB 1234567890

Invalid: AB1 1234567890 (more than 4 characters before the numbers) A1B1234567890 (less than 4 characters before the numbers) A1 B1234567890 (space amidst the first 4 characters instead of at the end)

+5
source share
5 answers

You can force the check using look-behind (?<=^[\p{L}\d\s]{4}) , which ensures that there are four valid characters up to a ten-digit number:

 ^[\p{L}\d]{1,4}\s{0,3}(?<=^[\p{L}\d\s]{4})\d{10}$ ^^^^^^^^^^^^^^^^^^^^ 

See demo

If you do not plan to support all Unicode letters, just replace \p{L} with [az] and use RegexOptions.IgnoreCase .

+6
source

Here you need a regex:

 ^(?=[A-Za-z0-9 ]{4}\d{10}$)[A-Za-z0-9]{1,4} *\d{10}$ 

It uses lookahead (?= ) To check if it follows 4 characters, either alnum, or a space, and then it goes back to where it was (beginning of line, consuming no characters).

Once this condition is met, the rest is an expression very similar to what you tried ( [A-Za-z0-9]{1,4} *\d{10} ).

Online tester

+4
source

I know this is stupid, but should work exactly as required.

 ^[A-Za-z\d]([A-Za-z\d]{3}|[A-Za-z\d]{2}\s|[A-Za-z\d]\s{2}|\s{3})[\d]{10}$ 
+2
source

Not sure what you are looking for, but it is possible:

 ^(?=.{14}$)[A-Za-z0-9]{1,4} *\d{10} 

demo

+2
source

Try the following:

Does not allow the combination char / space / char and starts with char:

 /\b(?!\w\s{1,2}\w+)\w(\w|\s){3}\d{10}/gm 

https://regex101.com/r/fF2tR8/2

0
source

All Articles