tags:

views:

60

answers:

3

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.

+1  A: 

^[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.

Jakob
it doesn't work
KhanS
Thanks Jakob, This worked for me
KhanS
No problem. Also, be aware of the bug mentioned by unicornaddict; I did not escape or move the hyphen like he did (until now).
Jakob
+1  A: 

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.

codaddict
+1, nice bug catch
Jakob
+1  A: 

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 whitespace 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 whitespace at the end of the string.

paxdiablo
+1 for avoiding a white space at the end.
codaddict