-8

I am trying to understand regular expressions, i find it really confusing to understand it. I need to know how to write a regular expression that ONLY matches strings, NO NUMBERS, NO SPECIAL CHARACTERS, just letters from A - Z. I have to say that I tried using \[a-z]\ but it didn't work as i wanted. These are some of the results that I want:

pe<.?ter -----> should return false
ale8 ---------> should return false
?ramon -------> should return false
tho<>?mass----> should return false

peter -----> should return true
alex ------> should return true
ramon -----> should return true
thomas ----> should return true
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
DRW02
  • 87
  • 2
  • 9
  • 2
    `^[a-zA-Z]+$` that should do it? From beginning to end. Has to be at least one letter – Matt Aug 01 '15 at 23:11
  • 1
    @Matt—perhaps with an *i* flag. – RobG Aug 01 '15 at 23:12
  • 3
    Numbers and special characters can be strings, even if there are no letters in the string. So what you're looking for is a regex that only accepts letters. – Matt Browne Aug 01 '15 at 23:12
  • Regular expressions are case sensitive, so you'll need to use the `i` flag: `/^[a-z]+$/i`. Or you can test for both uppercase and lowercase explicitly as the other Matt did. – Matt Browne Aug 01 '15 at 23:15
  • 1
    And you didn't find ANYTHING online ANYWHERE about doing this? Like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_parenthesized_substring_matches , http://perldoc.perl.org/perlrequick.html#Matching-repetitions or an interactive tool like http://regexpal.com/ ? You were already so close, how did you run out of patience? – dlamblin Aug 01 '15 at 23:17
  • [StackOverflow solution, but with digits][1] [1]: http://stackoverflow.com/questions/9351306/how-to-check-if-a-php-string-contains-only-english-letters-and-digits - you could delete digits from there – vir2al Aug 01 '15 at 23:19
  • http://regexpal.com/ is your friend. Test javascript regexes on the fly – RedMage Aug 01 '15 at 23:22

2 Answers2

5

This should work for you:

 var re = /^[a-z]+$/i; 

See here

baao
  • 71,625
  • 17
  • 143
  • 203
2

Your regex returns true if it find ONE letter from a to z, only lowercase, in your string.

To make what you want, use /^[a-zA-Z]+$/ or /^[a-z]+$/i.

^ make that your regex start from the begining of the string.

[a-zA-Z] make the regex to find one letter, lowercase OR uppercase (note that you could use instead the i modifier which make the search case insensitive).

+ make the regex to search for one or more times the previous element.

$ make sure that your regex end at the end of the string.

AdminXVII
  • 1,319
  • 11
  • 22