Reputation: 209
I'm validating a string("-test-") whether it contains hypens(-) at start and end of the string using regex. So i found an regex to restrict hypen at start and end of regex.
/^(?!-)[a-zA-Z0-9-' ]+[^-]$/i
This regex was validating as expected when the string contains more than one char("aa") with or without hypen. But its not working as expected when i'm simply passing one character string("a") without hypen.
And also these need to allow special characters and alphanumeric characters like "$abcd&". Need to restirct oly hypen at start and end of the string.
Could you guys help out of this..
Upvotes: 0
Views: 3318
Reputation: 627537
The pattern you have matches a string that consists of at least 2 chars because [a-zA-Z0-9-' ]+
needs 1 char to match and [^-]
requires another char to be present.
You may revamp the lookahead to also fail a string that ends with -
:
/^(?!-)(?!.*-$).+$/
^^^^^^^^
See the regex demo
Details
^
- start of a string(?!-)(?!.*-$)
- negative lookaheads that fail the match if the string starts with -
or ends with -
.+
- any 1 or more chars other than line break chars (use [\s\S]
to match any char)$
- end of string.An unrolled version for this pattern would be
^[^-]+(?:-+[^-]+)*$
See this regex demo
Details
^
- start of string[^-]+
- 1 or more chars other than -
(?:-+[^-]+)*
- 0+ sequences of
-+
- 1+ hyphens[^-]+
- 1 or more chars other than -
$
- end of string.Upvotes: 2
Reputation: 18555
To allow any character but only disallow hyphen at start and end:
^(?!-).*[^-]$
^
start of string(?!-)
look ahead if there is no hyphen.*
match any amount of any character[^-]
match one character, that is not a hyphen$
at the endUpvotes: 1