Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match only letters

Tags:

regex

How can I write a regex that matches only letters?

like image 904
Nike Avatar asked Sep 01 '10 12:09

Nike


People also ask

How do you regex only letters?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.

Which below regex is applicable for alphabets?

[A-Za-z] will match all the alphabets (both lowercase and uppercase).

What is the regular expression for characters?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.

How do you keep only letters in a string in python?

You can use the regular expression 'r[^a-zA-Z]' to match with non-alphabet characters in the string and replace them with an empty string using the re. sub() function. The resulting string will contain only letters.


2 Answers

Use a character set: [a-zA-Z] matches one letter from A–Z in lowercase and uppercase. [a-zA-Z]+ matches one or more letters and ^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively).

If you want to match other letters than A–Z, you can either add them to the character set: [a-zA-ZäöüßÄÖÜ]. Or you use predefined character classes like the Unicode character property class \p{L} that describes the Unicode characters that are letters.

like image 131
Gumbo Avatar answered Sep 19 '22 23:09

Gumbo


\p{L} matches anything that is a Unicode letter if you're interested in alphabets beyond the Latin one

like image 39
RobV Avatar answered Sep 18 '22 23:09

RobV