Validation
Letters Only Regex
Some fields should contain nothing but letters, such as a language code entered by hand, a single-word answer, or one part of a structured code. This pattern accepts one or more letters from A to Z in upper or lower case and rejects anything else, anchored at both ends. A digit, a space, a hyphen or an apostrophe anywhere in the input makes it fail. It is deliberately strict, so it is not a good fit for full human names, which often contain spaces, hyphens, apostrophes or letters outside the English alphabet. For those, a Unicode letter class with a few allowed separators works better.
Pattern (JavaScript)
/^[A-Za-z]+$/Starts at the start of the line/string, then a letter, one or more times, then the end of the line/string.
Examples
Matches
- ✓ hello
- ✓ Ali
- ✓ RegexLab
Does not match
- ✗ abc1
- ✗ Ali Test
- ✗ hello!
Try it
0 matches (JavaScript engine)
hello
Ali
RegexLab
abc1
Ali Test
hello!Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^[A-Za-z]+$/g;
const text = "hello";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^[A-Za-z]+$')
text = 'hello'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^[A-Za-z]+$/';
$text = 'hello';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^[A-Za-z]+$");
String text = "hello";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[A-Za-z]+$`)
text := "hello"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^[A-Za-z]+$");
var text = "hello";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^[A-Za-z]+$").unwrap();
let text = "hello";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^[A-Za-z]+$/
text = 'hello'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Should I use this for people's names?
- No. Real names include spaces, hyphens, apostrophes and accented letters. Use a looser rule such as ^[\p{L}' -]+$ with the u flag for name fields.
- How do I allow spaces between words?
- Use ^[A-Za-z]+( [A-Za-z]+)*$. It allows single spaces between words but not leading, trailing or double spaces.
- Is the check case-sensitive?
- The class lists both cases, so upper and lower case letters are both accepted. No i flag is needed.