I need a regex to use in Java to replace a String with "UNKNOWN" if the entire String is not "M", "F", or "M/F". In other words:
One odd case is "M/" or "F/" which should become "UNKNOWN". Please help, I'm dying over here.
I'm actually passing the regex into a framework via an xml mapping file, so I don't have programmatic control over how the output is formed. I can only pass in a regex, and what it gets replaced with.
You can use negative lookahead like this:
Pattern.compile("^(?!^(?:M|F|M/F)$).*$");
Using String#replaceAll you can do:
String replaced = str.replaceAll("^(?!^(?:M|F|M/F)$).*$", "UNKNOWN");
If 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