Reputation: 5018
I tried using this pattern
^[A-z]*[A-z,-, ]*[A-z]*
To match against a string that starts with multiple alpha characters (a-z) followed by multiple hyphens or spaces and ends with alpha characters, eg:
Azasdas- - sa-as
But it does not work.
Upvotes: 0
Views: 1246
Reputation: 75252
The currently accepted answer (^[A-Za-z][A-Za-z-]*[A-Za-z]$
) will only match strings that are at least two characters long--for example, it will match the string "AB"
, but not just "A"
or "B"
. Compare that to this regex:
^[A-Za-z]+([ -]+[A-Za-z]+)*$
By grouping the [ -]+
and the second [A-Za-z]+
together I'm saying, if there are any spaces and/or hyphens, they must be followed by more letters. The *
quantifier on the group makes it optional, so "A"
will match, while still meeting the requirement that the string start and end with a letter.
Upvotes: 1
Reputation: 160291
You don't want the commas, in a character range you also need to specify [A-Za-z\- ]
because the ASCII for A-Z and a-z aren't contiguous. You're missing some allowable spaces, and your last expression needs to account for the hypen.
You need something closer to this:
^([A-Za-z]*)-\s*([A-Za-z][A-Za-z -]*)([A-Za-z-]*)$
Depending on how you actually want to break things up. Without knowing the context behind the "chunks", it may or may not just be easier to split it apart on hyphens.
Edit
Actually, it's more like:
^([A-Za-z]*)([- ]*)([A-Za-z-]*)$
This is a word, followed by arbitrary spaces and hyphens, followed by a word that may contain a hyphen.
Upvotes: 1
Reputation: 3009
Try ^[A-Za-z][A-Za-z -]*[A-Za-z]$
^
indicates that the word should start with alphabets (A-Z or a-z) and then followed by any number of alphabets or hyphens. And then end with alphabets denoted by $
.
Also, you should not be using A-z because this will include unintended characters from ASCII range 91 to 96. See this table
Upvotes: 1