Ashok Kumar
Ashok Kumar

Reputation: 403

Removing salutations from full name using regex

I have names like "John Connele MCA MD" and "John O'Connele" and I used this regex "s*[A-Z]+(?:\.|\b)".

String fullName = "John O'Connele MCA MD";
fullName = fullName.replaceAll("s*[A-Z]+(?:\.|\b)","").trim;
System.out.println(fullName)

The purpose of the regex is to remove only the salutations and title the output I get is "John Connele" while correct output should be "John O'Connele"

Upvotes: 0

Views: 1144

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

   \W*\b[A-Z]+\b(?!'\b)\.?

See the regex demo.

Details

  • \W* - any 0+ non-word chars
  • \b - a word boundary (we need to match a whole word)
  • [A-Z]+ - 1+ uppercase ASCII letters
  • \b - end of word (a word boundary)
  • (?!'\b) - no ' followed with a word char is allowed immediately to the right of the current location
  • \.? - 1 or 0 . chars.

Java demo (note all backslashes are double inside string literals to denote literal backslashes, regex escapes):

String fullName = "John O'Connele MCA,MD.";
fullName = fullName.replaceAll("\\W*\\b[A-Z]+\\b(?!'\\b)\\.?","").trim();
System.out.println(fullName); // => John O'Connele

Upvotes: 2

Abimanyu
Abimanyu

Reputation: 511

You can try this.

\s[A-Z]{2,}+

Upvotes: 0

Related Questions