Reputation: 1102
I need to match a string using regular expression in which single quote
Minimum length of the string should be 2 and maximum length should not exceed 25 characters
There can be maximum of two spaces
I took some help from the following question on getting only a single occurrence of a character (in my case a single quote)
Javascript Regex to match only a single occurrence no more or less
and came up with this
^([^']([a-zA-Z])+(\s){0,1})+('){0,1}([a-zA-Z][^'])+$
Sample String that should get matched
Sample string that should not get matched
The problem:
Any help/advice regarding this would be appreciated.
EDIT 12-Sept-2013
The string should contain no special characters except single quote and space
Upvotes: 2
Views: 4633
Reputation: 425053
Use a look-ahead to assert the quote usage and a simple repetition for the overall size:
^(?=([^']*[a-zA-Z]')?[^']+$).{2,25}$
See a live demo working correctly with all examples given.
Upvotes: 0
Reputation: 664599
I'm using lookahead to check the conditions on their own:
/^(?=[a-z ']{2,25}$)(?=(?:\S+\s){0,2}\S*$)(?:[^']*|[^']*?[a-z]'[^']+)$/i
^ # from start of string
(?=[a-z ']{2,25}$) # 2 to 25 of the allowed chars until end of string
(?=(?:\S+\s){0,2}\S*$) # at most two spaces until end of string
(?: # either
[^']* # no apostrophe
| # or
[^']*?[a-z]'[^']+ # exactly one apostrophe preceded by alphabet letter
)$ # to end of string
But they better be separated in code. So use
str.length >= 2 && str.length <= 25
&& /^(?:\S+\s){0,2}\S*$/.test(str)
&& /^[a-z ]*(?:[a-z]')?[a-z ]+$/i.test(str)
Upvotes: 4