Suzane
Suzane

Reputation: 203

regex expression to allow only certain charaters Capital letters A-Z ' - and space

I am new to regular expression. I have a requirement to validate a string in regular expression -

 Capital letters A-Z  '  - and space 

I am new to this regex concepts -

and tried  [A-Z,',-]*    -> Any character in this class [A-Z,',/]. any number of repeatitions.

I tried to verify and i am not very confident because i havent specified that this regular expression can validate spaces even.. I appreciate if someone can give suggestion or provide little info if i am missing something

Upvotes: 0

Views: 2752

Answers (4)

lhrec_106
lhrec_106

Reputation: 630

For Capital letters A-Z ' - and space You could use [A-Z\s\'\-] \s is for space, \' is for ', \- is for - , comma is not needed

Upvotes: 0

Alex1985
Alex1985

Reputation: 658

You don't separate chars with a comma in [], so you should use [A-Z' \-]* You need to use \- because '-' has special meaning inside [].

Upvotes: 2

anubhava
anubhava

Reputation: 785186

Commas are not needed inside character class. So following should work for you:

[A-Z' -]+

Which means:

A-Z      - Capital letters from A-Z (Range)
'        - Single Quote
" "      - Space (double quotes only to show you space)
-        - Hyphen (must appear as 1st or last in character class in order to avoid escaping
[A-Z' -]+ - Match 1 or more of the above allowed characters

Upvotes: 2

tr33hous
tr33hous

Reputation: 1642

You need to escape special chars:' and -

[A-Z\-\']* should work.

Upvotes: 0

Related Questions