What is the regex for letters?
Short answer: [a-zA-Z] matches any single letter, uppercase or lowercase. Add + to match whole words of letters, and wrap it in ^...$ to check that a text has only letters:
[a-zA-Z] one letter
[a-zA-Z]+ one or more letters in a row
^[a-zA-Z]+$ the whole text is letters
[A-Z] one uppercase letter
[a-z] one lowercase letter[a-zA-Z] only covers the English alphabet. For letters with accents, such as é or ñ, use [^\W\d_] in Python or \p{L} with the u flag in JavaScript.
[a-zA-Z]+ finds English letters, fullmatch() checks the whole text and [^\W\d_]+ also keeps letters with accents.
Regex for letters cheat sheet
| What you want | Regex | Matches in "Hello World 123" |
|---|---|---|
| Any letter | [a-zA-Z] | H, e, l... |
| Words made of letters | [a-zA-Z]+ | Hello, World |
| Uppercase letters | [A-Z] | H, W |
| Lowercase letters | [a-z]+ | ello, orld |
| Only letters, whole text | ^[a-zA-Z]+$ | No match: it has spaces and digits |
| Anything that is not a letter | [^a-zA-Z] | The spaces and 1, 2, 3 |
| Words that start with a capital | \b[A-Z]\w* | Hello, World |
| Any letter in any language (Python) | [^\W\d_] | Also é, ü, ñ |
| Any letter in any language (JavaScript) | /\p{L}/u | Also é, ü, ñ |
Match letters in Python
Python uses the re module. Write patterns as raw strings (r"...") so backslashes stay as they are:
import re
text = "Hello World 123"
print(re.findall(r"[a-zA-Z]+", text)) # ['Hello', 'World']
print(re.findall(r"[A-Z]", text)) # ['H', 'W']
print(bool(re.fullmatch(r"[a-zA-Z]+", "Hello"))) # True
print(bool(re.fullmatch(r"[a-zA-Z]+", "Hello1"))) # Falsere.findall() returns every match in a list, and re.fullmatch() checks that the whole text follows the pattern. To ignore case, use [a-z] with flags=re.I.
Match letters in JavaScript
const text = "Hello World 123";
console.log(text.match(/[a-zA-Z]+/g)); // ["Hello", "World"]
console.log(/^[a-zA-Z]+$/.test("Hello")); // true
console.log(/^[a-zA-Z]+$/.test("Hello1")); // false
console.log("Hello World".match(/[a-z]+/gi)); // ["Hello", "World"]The g flag returns every match, not only the first one, and i ignores case. .test() returns true or false.
