正则表达式找到&替换特定的子串

时间:2018-03-15 17:33:23

标签: java regex regex-lookarounds

我想要正则表达式找到&将以下给定字符串中的第一个和第三个csv单词替换为单词rownum

NONE

我尝试过以下正则表达式,但在String str = "select dummy,rownum,rowid as \"rownum\",rownum as order_number from dual"; 字词之前或之后替换了逗号,

rownum

实际输出:str = str.replaceAll("(?i)[^\"A-Z0-9]rownum[^$\"A-Z0-9]"," NONE ")

预期输出:select dummy NONE rowid as "rownum" NONE as order_number from dual

2 个答案:

答案 0 :(得分:1)

如果您希望避免替换"rownum",因为它被"包围,那么您可以使用look-around机制禁止"之前或之后

String str = "select dummy,rownum,rowid as \"rownum\",rownum as order_number from dual";
str = str.replaceAll("(?i)(?!<\")\\brownum\\b(?!\")"," NONE ");
System.out.println(str);

输出:select dummy, NONE ,rowid as "rownum", NONE as order_number from dual

但该解决方案仅对此特定情况有效。如果你有其他的,你应该搜索SQL解析器而不是RegEx。

答案 1 :(得分:0)

你可以试试这个,它的作品

str = str.replace("rownum", "NONE");
str = str.replace("\"NONE\"", "\"rownum\"");