gpt4 book ai didi

java regex matcher.replaceAll 与组

转载 作者:行者123 更新时间:2023-11-30 10:08:46 25 4
gpt4 key购买 nike

我正在尝试将一种语法替换为另一种语法,我正在通过正则表达式执行此操作,我想将一种模式替换为另一种模式。

Pattern pattern = Pattern.compile("length\\((?<field>[a-zA-Z]+)\\)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(statement);

if (matcher.find())
statement = matcher.replaceAll("LEN(" + matcher.group("field") + ")");
return statement;

这是一件简单的事情,我想替换所有(循环)匹配项并将它们替换为另一个文本。然而,我正在努力让小组进行动态迭代。

Expected :select *,LEN(devise) lendevise,LEN(marche) lenmarche,LEN(nature) lennature from tableX where nseq='0'

Actual :select *,LEN(devise) lendevise,LEN(devise) lenmarche,LEN(devise) lennature from tableX where nseq='0'

所以你可以在这里注意到。组值总是替换为第一个匹配项的组,而不是被替换的相应匹配项?

是否有一种有效的“最佳”方式来做到这一点?我想避免(如果可能的话)将不同的组放在单独的数组中。

最佳答案

我建议将解决方案简化为单个 replaceAll 调用,这将替换内联的所有匹配项,并且不会像您遇到的那样造成任何麻烦:

statement = statement.replaceAll("length\\(([a-zA-Z]+)\\)", "LEN($1)");

参见 regexJava demo .

String s = "select *,length(devise) lendevise,length(marche)  lenmarche,length(nature) lennature from tableX where nseq='0'";
System.out.println(s.replaceAll("length\\(([a-zA-Z]+)\\)", "LEN($1)"));
// => select *,LEN(devise) lendevise,LEN(marche) lenmarche,LEN(nature) lennature from tableX where nseq='0'

请注意,([a-zA-Z]+) 形成一个带编号的捕获组,稍后可以使用 $1 占位符(或替换反向引用)访问其值).

关于java regex matcher.replaceAll 与组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53631127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com