Regex to match only strings containing alphabets

Viewed 75

I have a list of strings:

Mr 1
Mr 1-ta
Mr Charles Darwin
Mr John Smith
Mr 100

and I want to write a regex where it only matches the string with no numeric elements in it, in this case, the following strings should not be matched

Mr 1
Mr 1-ta
Mr 100

and the strings that will be matched is:

Mr Charles Darwin
Mr John Smith

The regex I currently have is:

^(Mr\s)(.*)$

How do i modify it in such a way where it would only consider alphabetical elements after the Mr ? There is a notation [a-zA-Z], but how do I combine it with the (.*) notation?

2 Answers

The comment-answer by @JvdV is fine, but you could also do this simply using a negative lookahead:

^(?!.*\d)Mr(?: \w+)+$

Demo

Explanation of regex:

^          from the start of the string
(?!.*\d)   assert that no digits are present
Mr         then match "Mr"
(?: \w+)+  followed by one or more name terms (a name being \w+)
$          end of the string

You can just use \D to allow it match any non-digit after matching Mr and following space:

^Mr\s\D+$

RegEx Demo

Explanations:

  • ^: Start
  • Mr\s: Match Mr followed by a whitespace
  • \D+: Match 1+ non-digit characters
  • $: End
Related