Skip to content Skip to sidebar Skip to footer

Regex With Any Term Optional And In Any Order (javascript Or Java)

I have a string like this '%d-%m-%Y' , any of these terms can be in any order, and the dash can be another string (%x). I want to get the result as : '%d %m %Y' . I baked a straig

Solution 1:

I'm not sure about your requirements but maybe a 2-step approach would work:

  1. extract the permutations of %d.*%m.*%Y, e.g. using temp = input.replaceAll(".*(%(?:d|m|Y).*%(?:d|m|Y).*%(?:d|m|Y)).*", "$1")

  2. replace the content between %d, %m and %Y, e.g. using temp.replaceAll("(?<=%(?:d|m|Y))(.*?)(?=%(?:d|m|Y))", " ");

Java example:

String input ="xx %Y-%m-%d xx";    
String temp = input.replaceAll( ".*(%(?:d|m|Y).*%(?:d|m|Y).*%(?:d|m|Y)).*", "$1" );
String output = temp.replaceAll( "(?<=%(?:d|m|Y))(.*?)(?=%(?:d|m|Y))", " " );

System.out.println(output);   //results in "%Y %m %d"

Notes: - This requires 3 components, i.e. %d-%m would not match. - "%d-%d" would still be allowed, checking that with regex would be hard.

Update: the following expression should allow for 1-3 components: .*?(%(?:d|m|Y)(?:.*%(?:d|m|Y)){0,2}).* in step one.

Post a Comment for "Regex With Any Term Optional And In Any Order (javascript Or Java)"