Reputation: 1178
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
Reputation: 21
Use this
String s = "Dna Jane XXX";
System.out.println(s.replaceAll("(Dna|Dra|Dr) ", ""));
Upvotes: 2
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:
Upvotes: 4