gpt4 book ai didi

javascript - Rhino:如何让Rhino计算Java字符串上的RegEx表达式?

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:17 25 4
gpt4 key购买 nike

searchValue 是 RegEx 表达式时,我在从 Rhino 调用 Java String 对象上的 .replace(searchValue, newValue) 时遇到问题。当 searchValue 不是 RegEx 表达式,或者在从 JavaScript 内部启动的字符串上调用该方法时,此方法可以正常工作。

示例:

示例 Java 对象和返回字符串的方法

public class MyTestObject {
public String returnStringValue() {
return " This is a string with spaces ";
}
}

设置Rhino,创建Java对象

import java.io.FileNotFoundException;
import javax.script.*;

public class TestRhino{

public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
// Create my Java Object
MyTestObject testObject = new MyTestObject();

// Initiate the JavaScript engine
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Compilable compEngine = (Compilable)engine;

// evaluate my JavaScript file; add my Java object to it
engine.eval(new java.io.FileReader("MyJavaScriptFile.js"));
engine.put("testObject", testObject); // this adds my Java Object to Rhino

// Invoke my javaScript function
Invocable inv = (Invocable) engine;
Object returnVal = inv.invokeFunction("testFunction");

// print out the result
System.out.println(returnVal); // should print "ThisisaString" to the console
}
}

我的 JavaScript 函数(此代码不能以任何方式修改)。

function testFunction() {
let myString = testObject.returnStringValue();
return myString.replace(/\s/g,""); // Error!
}

这会引发错误 Java 构造函数替换匹配 JavaScript 参数类型(函数、字符串)的选择不明确;候选构造函数是:class java.lang.String Replace(java.lang.CharSequence,java.lang.CharSequence)

但是,当我的JavaScript函数修改如下时,Rhino返回预期值,并且没有抛出错误。

function testFunction() {
let myString = testObject.returnStringValue();
return myString.replace("T", "P"); // Phis is a string with spaces
}

以下 JavaScript 函数在使用 Rhino 调用时也可以工作。

function testFunction() {
return " This is a string with spaces ".replace(/\s/g,""); // Thisisastringwithspaces
}

我正在寻找一种无需修改 JavaScript 代码即可实现上述功能的方法。我只能修改Java代码。

注意:这适用于 Nashorn(从 Java1.8 开始的默认 JavaScript 引擎),但是我必须使用 Rhino(Java 1.7 之前的默认 JavaScript 引擎)。

最佳答案

我的猜测是Java代码调用

replace(null, null);

String中的方法类,因此不知道它是否应该执行 -

replace(char oldChar, char newChar);

replace(CharSequence target, CharSequence replacement);

将 Java 调用中的参数转换为:

replace((CharSequence) null, (CharSequence) null);

关于javascript - Rhino:如何让Rhino计算Java字符串上的RegEx表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43141353/

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