Java RegEx 没有替换所有预期的模式

我想要实现的只是用 ILIKE 代替比较等于,而不是赋值语句。


IE


SELECT * FROM db WHERE SUBJECT_TYPE = 'Person';

应该替换为


SELECT * FROM db WHERE SUBJECT_TYPE ILIKE 'Person';

然而


SET session ABC.VAR = 5;

应该保持不变。


为此,我正在尝试使用前瞻性,以便在等于 (=)之前没有SET。


爪哇


String str = "SELECT * FROM db WHERE SUBJECT_TYPE = 'Person' AND PREDICATE = 'name' AND OBJECT_VALUE = 'John' AND VERSION = '0' "

final Pattern EQUALS_ILIKE_PATTERN = Pattern.compile("(?i)((^((?!SET)[^=])+?)\\s*)=");


final Matcher matcher = EQUALS_ILIKE_PATTERN .matcher(str);


while (matcher.find())

{

    final String fromString = matcher.group(0);


    str = matcher.replaceAll("$1 ILIKE");

}


System.out.println(str);

实际结果:


SELECT * FROM DB WHERE SUBJECT_TYPE ILIKE 'Person' AND PREDICATE = 'name' AND OBJECT_VALUE = 'John' AND VERSION = '0'


预期结果:


SELECT * FROM DB WHERE SUBJECT_TYPE ILIKE 'Person' AND PREDICATE ILIKE 'name' AND OBJECT_VALUE ILIKE 'John' AND VERSION ILIKE '0'


这里的实际结果不会替换所有必要的等号 (=)。


MM们
浏览 80回答 1
1回答

DIEA

我们可以通过单行调用来做到这一点String#replaceAll: String str = "SELECT * FROM db WHERE SUBJECT_TYPE = 'Person' AND PREDICATE = 'name' AND OBJECT_VALUE = 'John' AND VERSION = '0' ";str = str.replaceAll("(WHERE|AND)\\s+(\\S+)\\s+=(?=\\s*'[^'+]+')", "$1 $2 ILIKE");System.out.println(str);此输出(格式化为可读性):SELECT *FROM dbWHERE    SUBJECT_TYPE ILIKE 'Person' AND    PREDICATE ILIKE 'name' AND    OBJECT_VALUE ILIKE 'John' AND    VERSION ILIKE '0'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java