Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for everything but "M", "F", "M/F"

Tags:

regex

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:

  • String "M" stays "M"
  • String "F" stays "F"
  • String "M/F" stays "M/F"
  • Anything else becomes "UNKNOWN"

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.

like image 383
Mario Avatar asked Oct 08 '22 06:10

Mario


1 Answers

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");
like image 100
anubhava Avatar answered Oct 13 '22 11:10

anubhava