How to write regex that excludes the name after Mr. when finding words at the start of a sentence?

Viewed 52

I currently have to make a regex that matches the first words at the start of sentences. I've currently done to the point where it matches the first word at the start of the paragraph and the rest, the first words that come after ". The problem that I have here is that 'Sherwood' which is obviously a name, shouldn't be matched but is because it matches the regex which I have written. 'Capital starting letter, comes directly after . and a space'

How can I change my code to exclude the name that comes after Mr. or Dr.?

Current regex: ((^[A-Z]+[a-z]*[A-Z]*[a-z]*|(?<=\")[A-Z]+[a-z]*[A-Z]*[a-z]*)|(?<=\.\s)[A-Z]+[a-z]*[A-Z]*[a-z]*)

I've used regex101.com as a reference.

1 Answers

You could shorten the pattern with the alternations to a single non capture group containing the 3 patterns that are allowed for the start of the string.

As you are already using a lookbehind assertion, you can exclude Mr. of Dr. to the left using a negative lookbehind:

(?:^|(?<=")|(?<=\.\s))(?<![MD]r\. )[A-Z]+[a-z]*[A-Z]*[a-z]*

Regex demo

You might also first match an uppercase char, and then do the assertions to prevent the alternation with the lookbehind assertions to fire on every position when there is no match.

[A-Z](?<=".|\.\s.|^.)(?<![MD]r\. .)(?:[A-Z]*[a-z]*){2}

Regex demo

Related