简体   繁体   English

Java正则表达式替换和条件

[英]Java regex replacement with and condition

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. 我想要做的是,使用Java正则表达式,如果它不是“顺序”序列,则替换“Or”序列。 Thereby if the sequence starts with "Or" and it does not end with "der" I would like to do a replace: 因此,如果序列以“Or”开头并且它不以“der”结尾,我想做一个替换:

Eg: 例如:

  • findByNameOrAge expected -> findByName Or Age findByNameOrAge expected - > findByName或Age
  • findByNameOrderAge expected -> findByNameOrderAge (Keep the same value) findByNameOrderAge expected - > findByNameOrderAge(保持相同的值)

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 "));

Your regex (?=^der) matches Or and uses a positive lookahead to assert what follows is the start of the string ^ followed by der 你的正则表达式(?=^der)匹配Or并使用正向前瞻来断言后面是字符串的开头^后跟der

Instead, you could use a negative lookahead (?! to assert that what follows Or is not der and then replace with or 相反,你可以使用负向前瞻(?!来断言后面的内容Or不是der ,然后用or替换

Or(?!der)

Regex Demo 正则表达式演示

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

Java Demo Java演示

Try this one: Or(?!der) , it will check whether Or is followed by der or not. 试试这个: Or(?!der) ,它会检查Or是否跟着der it will replace Or if it is not followed by der ,skip otherwise. 它将替换Or如果它没有被der跟随,则跳过其他方式。

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) Or匹配字符或字面(区分大小写)

Negative Lookahead (?!der) 否定前瞻(?!der)

Assert that the Regex below does not match 断言下面的正则表达式不匹配

der matches the characters der literally (case sensitive) der匹配字符der字面上(区分大小写)

String regex = "[Oo]r(?!der)"; use this as regular expression. 使用它作为正则表达式。 It will also include the word "or" with uper case and lower case 'o'. 它还包括单词“or”和uper case以及小写“o”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM