How to use regex in Java to remove something from the name?

Viewed 83

I'm learning Regex in Java and I receive a String name from a service. The String could be in this form:

"Dl Frank Joseph", 
"Dna Jane XXX", 
"Dra XXX YYY", 
"Dr XXX YYY",
"XXX YYY". 

So if the name is "XXX YYY" it will remain the same, but if the name contains "Dl", "Dna", "Dra", "Dr" then I should delete this word and remain only the name "XXX YYY".

How can I do that?

2 Answers

You can use the regex, ^(?i)(Dl|Dna|Dra|Dr)\\s+.

Demo:

import java.util.stream.Stream;

class Main {
    public static void main(String[] args) {
        Stream.of(
                "Dl Frank Joseph", 
                "Dna Jane XXX", 
                "Dra XXX YYY", 
                "Dr XXX YYY", 
                "XXX YYY"
            ).forEach(s -> System.out.println(s.replaceAll("^(?i)(Dl|Dna|Dra|Dr)\\s+", "")));
    }
}

Output:

Frank Joseph
Jane XXX
XXX YYY
XXX YYY
XXX YYY

Explanation of the regex at regex101:

enter image description here

Use this

String s = "Dna Jane XXX";
System.out.println(s.replaceAll("(Dna|Dra|Dr) ", ""));
Related