I am looking for a regex pattern that ensures the user puts in a single lower case word with only letters of the alphabet. Basically they are picking a subdomain. Thanks in advance
I am looking for a regex pattern that ensures the user puts in a single lower case word with only letters of the alphabet. Basically they are picking a subdomain. Thanks in advance
Share Improve this question edited Aug 8, 2010 at 11:27 kennytm 523k110 gold badges1.1k silver badges1k bronze badges asked Aug 8, 2010 at 11:20 abarrabarr 1,1404 gold badges13 silver badges28 bronze badges 5- Why are you limiting your users to lower-case, presumably ASCII letters for subdomains? That's not all that's allowed in DNS. – Nicholas Knight Commented Aug 8, 2010 at 11:22
- 1 What language? RegEx dialects have different features, so it's important to know. Java? .NET? Javascript? Perl? Python? Ruby? Something else? – Oded Commented Aug 8, 2010 at 11:22
- 1 Why not just force the input into lowercase afterwards. It seems unnecessary for an input field to fail validation because you don't allow uppercase characters. Domains are case-insensitive, so however they write the sub-domain doesn't matter. Also, hyphens are allowed in domain names. – Andy E Commented Aug 8, 2010 at 11:23
- you are right ... forget the lowercase. JS for the programing language and a-z – abarr Commented Aug 8, 2010 at 11:24
- 7 @Gumbo: Given that he's from Australia I'd guess he means the Australian alphabet, i.e. [z-ɐ]. – Mark Byers Commented Aug 8, 2010 at 11:25
4 Answers
Reset to default 9The character class [a-z]
describes one single character of the alphabet of lowercase letters a
–z
. If you want if an input does only contain characters of that class, use this:
^[a-z]+$
^
and $
mark the start and end of the string respectively. And the quantifier +
allows one or more repetitions of the preceding expression.
^[a-z]+$ Will find one and only one lower-case word, with no spaces before or after the word.
/^[a-z]+$/
make sure you aren't using 'i' after the last slash
/[a-z]+/
if you are searching for any words within the context
If you want to find all occurrences of lowercase-only ASCII-char words, you can use
text.match(/\b[a-z]+\b/g)
See the regex demo.
Details:
\b
- a word boundary[a-z]+
- one or more (+
) lowercase ASCII letters\b
- a word boundary
The g
flag makes it extract all occurrences.
See the JavaScript demo:
const text = "123456789 Ticket number (CO2) text";
console.log(text.match(/\b[a-z]+\b/g));