IS:
String: "DARTH WEDR DR MRS"
Regex: "(.*?DR)\\s(-|MRS?|MI?SS?)?$"
This regex operation cant remove MRS and leave only DR.

SHOULD:
String: "DARTH WEDR DR MRS".replaceAll("(.*?DR)\\s(-|MRS?|MI?SS?)?$", "");
Output: "DARTH WEDR DR"
Abbreviation is always at the end, but some names can have abbreviation in their names, so it should be <space> DR <space> to read at the end to escape the problem with abbreviation in the names.
EXAMPLE:
BRUCE WAYNE MR
GAL GADOT DR MS
GOD ZILADR DR MRS
Im out of ideas. Any idea?
I suggest using
.replaceAll("(.*?\\sDR)(?:\\s+(?:-|MRS?|MI?SS?))?$", "$1");
^^^ ^^^ ^ ^^ ^^
See the regex demo
NOTES:
DR enclosed with whitespaces, \s is added before DR(?:\s+(?:-|MRS?|MI?SS?))? matches 1 or 0 occurrences of 1+ whitespaces followed with -, MR, MRS, MS, MSS,MIS or MISSIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With