Reputation: 1287
I have an asp.net regularexpressionvalidator that I need to match on a textbox. If there is any text, logically the rules are as follows:
The text must be at least three characters, after any trimming to remove spaces. Characters allowed are a-zA-Z0-9-' /\&.
I'm having major pain trying to construct an expression that will allow a space as the thrid character only if there is a fourth non-space character.
Can anyone suggest an expression? My last attempt was:
^[a-zA-Z0-9-'/\\&\.](([a-zA-Z0-9-'/\\&\.][a-zA-Z0-9-' /\\&\.])|([a-zA-Z0-9-' /\\&\.][a-zA-Z0-9-'/\\&\.]))[a-zA-Z0-9-' /\\&\.]{0,}$
but that does not match on 'a a'.
Thanks.
Upvotes: 0
Views: 4935
Reputation: 126045
Simplifying your allowed characters to be a-z and space for clarity, doesn't this do it?
^ *[a-z][a-z ]+[a-z] *$
Ignore spaces. Now a letter. Then some letters or spaces. Then a letter. Ignore more spaces.
The full thing becomes:
^ *[a-zA-Z0-9-'/\\&\.][a-zA-Z0-9-'/\\&\. ]+[a-zA-Z0-9-'/\\&\.] *$
Upvotes: 0
Reputation: 336098
OK, now this is all in one regex:
^\s*(?=[a-zA-Z0-9'/\\&.-])([a-zA-Z0-9'/\\&.\s-]{3,})(?<=\S)\s*$
Explanation:
^ # Start of string
\s* # Optional leading whitespace, don't capture that.
(?= # Assert that...
[a-zA-Z0-9'/\\&.-] # the next character is allowed and non-space
)
( # Match and capture...
[a-zA-Z0-9'/\\&.\s-]{3,} # three or more allowed characters, including space
)
(?<=\S) # Assert that the previous character is not a space
\s* # Optional trailing whitespace, don't capture that.
$ # End of string
This matches
abc
aZ- &//
a ab abc x
aaa
a a
and doesn't match
aa
abc!
a&
Upvotes: 3