elvis
elvis

Reputation: 1178

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

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?

Upvotes: 1

Views: 100

Answers (2)

Use this

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

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79035

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

Upvotes: 4

Related Questions