Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace operation if exist in java

IS:

String: "DARTH WEDR DR MRS"
Regex: "(.*?DR)\\s(-|MRS?|MI?SS?)?$"

This regex operation cant remove MRS and leave only DR. enter image description here

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?

like image 919
JuBz Avatar asked Sep 11 '26 09:09

JuBz


1 Answers

I suggest using

.replaceAll("(.*?\\sDR)(?:\\s+(?:-|MRS?|MI?SS?))?$", "$1");
                 ^^^   ^^^   ^ ^^              ^^

See the regex demo

NOTES:

  • Since you need to match DR enclosed with whitespaces, \s is added before DR
  • The whole trailing part is optional, so the whitespace must also be optional. (?:\s+(?:-|MRS?|MI?SS?))? matches 1 or 0 occurrences of 1+ whitespaces followed with -, MR, MRS, MS, MSS,MIS or MISS
  • To keep the starting text, replace with the backreference to Group 1.
like image 143
Wiktor Stribiżew Avatar answered Sep 12 '26 23:09

Wiktor Stribiżew