为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MM们 2023-02-16 15:36:34
我想要实现的只是用 ILIKE 代替比较等于,而不是赋值语句。IESELECT * 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'这里的实际结果不会替换所有必要的等号 (=)。
查看完整描述

1 回答

?
DIEA

TA贡献1820条经验 获得超2个赞

我们可以通过单行调用来做到这一点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'


查看完整回答
反对 回复 2023-02-16
  • 1 回答
  • 0 关注
  • 79 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信