Charanraj Golla
Charanraj Golla

Reputation: 1102

Regular expression for matching single occurrence of ' (single quote) coming only between alphabets not on start or end of the string

I need to match a string using regular expression in which single quote

  1. can appear zero or one time
  2. should not be at the start or end of the string
  3. should have at least one alphabet before it (if single quote appears)

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][^'])+$

Regular expression visualization

Edit live on Debuggex

Sample String that should get matched

Sample string that should not get matched

The problem:

  1. My regEx matches string starting with space
  2. It does not match shanon d'cos and shanon d'costa but matches shanon d'cost
  3. Maximum of 25 character is also not working

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

Answers (2)

Bohemian
Bohemian

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

Bergi
Bergi

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

Related Questions