Powisss
Powisss

Reputation: 1142

Regex for fixed number of letters with space inbetween

I want to have a regex that filters string in which only 4 letters and if needed a space inbeween, followed by 4 letters again and so on is acceptable.

OK: 
abcd efgh ijkl mnop
aasd asdd
asda

Not OK:
abcsd asda
asd asdd asdd
asdd asdd asdds
asdd  asdd  asds

So far I can match just first 4 letter word with space or without.

^(| )[a-z\s]{0,4}$(| )

So this fails after I add a character or another space as e.g. asdf s <- fails. What am I missing? Thanks!

Upvotes: 1

Views: 47

Answers (1)

The fourth bird
The fourth bird

Reputation: 163277

The pattern that you tried matches an optional space at the start and at the end an can match 0-4 times a char a-z or a whitespace char and could possibly also match an empty string as everything is optional.

The pattern could be matching 4 times a-z and repeat 0+ times a space followed by 4 times a-z

^[a-z]{4}(?: [a-z]{4})*$

Regex demo

Note that in the first line ijklm is 5 chars instead of 4 and \s could possibly also match a newline.

Upvotes: 3

Related Questions