Java regex replacement with and condition

Viewed 91

I have a question. What I would like to do is, using Java regex, replace a "Or" sequence if it isn't an "Order" sequence. Thereby if the sequence starts with "Or" and it does not end with "der" I would like to do a replace:

E.g.:

  • findByNameOrAge expected -> findByName Or Age
  • findByNameOrderAge expected -> findByNameOrderAge (Keep the same value)

I've tried same regex sequence, however, without luck.

    String value = "findByNameOrAge";
    String value2 = "findByNameOrderByAge";
    String regex = "Or(?=^der)";
    System.out.println(value.replaceAll(regex, " or "));
    System.out.println(value2.replaceAll(regex, " or "));
3 Answers

Your regex (?=^der) matches Or and uses a positive lookahead to assert what follows is the start of the string ^ followed by der

Instead, you could use a negative lookahead (?! to assert that what follows Or is not der and then replace with or

Or(?!der)

Regex Demo

String regex = "Or(?!der)";

Java Demo

Try this one: Or(?!der), it will check whether Or is followed by der or not. it will replace Or if it is not followed by der,skip otherwise.

String value = "findByNameOrAge";
String value2 = "findByNameOrderByAge";
String regex = "Or(?!der)";
System.out.println(value.replaceAll(regex, " or "));
System.out.println(value2.replaceAll(regex, " or "));

check demo here

Explanation

Or(?!der)

Or matches the characters Or literally (case sensitive)

Negative Lookahead (?!der)

Assert that the Regex below does not match

der matches the characters der literally (case sensitive)

String regex = "[Oo]r(?!der)"; use this as regular expression. It will also include the word "or" with uper case and lower case 'o'.

Related