我要实现的所有目的是用ILIKE代替比较性等式,而不是赋值语句。



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 =
  '名称'AND OBJECT_VALUE ='约翰'AND版本='0'


预期结果:


  SELECT * FROM db WHERE SUBJECT_TYPE ILIKE'Person'and PEDICATE
  ILIKE'名称'和OBJECT_VALUE ILIKE'约翰'和版本ILIKE'0'


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

最佳答案

我们可以通过单行调用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 db
WHERE
    SUBJECT_TYPE ILIKE 'Person' AND
    PREDICATE ILIKE 'name' AND
    OBJECT_VALUE ILIKE 'John' AND
    VERSION ILIKE '0'

关于java - Java RegEx不会替换所有预期的模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56746878/

10-10 19:54