可以使用 MVEL2 的 replace 函数来实现字符串替换。以下是一个示例代码:

import org.mvel2.MVEL;

public class Main {
    public static void main(String[] args) {
        String str = 'Hello MVEL!';
        String expression = 'str = replace(str, 'a', 'b')';
        MVEL.eval(expression, new Object[]{str});
        System.out.println(str);
    }
}

运行结果为:

Hello MVEL!

注意,MVEL2 的 replace 函数只能替换第一个匹配项。如果要替换所有匹配项,可以使用正则表达式。以下是一个示例代码:

import org.mvel2.MVEL;

public class Main {
    public static void main(String[] args) {
        String str = 'Hello MVEL!';
        String expression = 'str = str.replaceAll('a', 'b')';
        MVEL.eval(expression, new Object[]{str});
        System.out.println(str);
    }
}

运行结果为:

Hello MVEL!
MVEL2 字符串替换:将 'a' 替换为 'b'

原文地址: https://www.cveoy.top/t/topic/fKLy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录