KhanS
KhanS

Reputation: 1195

Regular expression to match maximium of five words

I have a regular expression

^[a-zA-Z+#-.0-9]{1,5}$

which validates that the word contains alpha-numeric characters and few special characters and length should not be more than 5 characters.

How do I make this regular expression to accept a maximum of five words matching the above regular expression.

Upvotes: 3

Views: 4732

Answers (3)

paxdiablo
paxdiablo

Reputation: 882206

I believe this may be what you're looking for. It forces at least one word of your desired pattern, then zero to four of the same, each preceded by one or more white-space characters:

    ^XX(\s+XX){0,4}$

where XX is your actual one-word regex.

It's separated into two distinct sections so that you're not required to have white-space at the end of the string. If you want to allow for such white-space, simply add \s* at that point. For example, allowing white-space both at start and end would be:

    ^\s*XX(\s+XX){0,4}\s*$

Upvotes: 3

codaddict
codaddict

Reputation: 455350

You regex has a small bug. It matches letters, digits, +, #, period but not hyphen and also all char between # and period. This is because hyphen in a char class when surrounded on both sides acts as a range meta char. To avoid this you'll have to escape the hyphen:

^[a-zA-Z+#\-.0-9]{1,5}$

Or put it at the beg/end of the char class, so that its treated literally:

^[-a-zA-Z+#-.0-9]{1,5}$
^[a-zA-Z+#.0-9-]{1,5}$

Now to match a max of 5 such words you can use:

^(?:[a-zA-Z+#\-.0-9]{1,5}\s+){1,5}$

EDIT: This solution has a severe limitation of matching only those input that end in white space!!! To overcome this limitation you can see the ans by Jakob.

Upvotes: 1

Jakob
Jakob

Reputation: 24370

^[a-zA-Z+#\-.0-9]{1,5}(\s[a-zA-Z+#\-.0-9]{1,5}){0,4}$

Also, you could use for example [ ] instead of \s if you just want to accept space, not tab and newline. And you could write [ ]+ (or \s+) for any number of spaces (or whitespaces), not just one.

Edit: Removed the invalid solution and fixed the bug mentioned by unicornaddict.

Upvotes: 3

Related Questions