开发者

Regular expression to match maximium of five words

开发者 https://www.devze.com 2022-12-26 11:10 出处:网络
I have a regular expression ^[a-zA-Z+#-.0-9]{1,5}$ which validates that t开发者_如何学Che word contains alpha-numeric characters and few special characters and length should not be more than 5 cha

I have a regular expression

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

which validates that t开发者_如何学Che 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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号