Regexp in String.replaceAll() not working? [message #1844804] |
Sun, 26 September 2021 05:48  |
Eclipse User |
|
|
|
Hi,
I'm probably overlooking something very trivial but I seem unable to use regexp in search and replace in JS (Rhino) EASE scripts.
No regexp whatsoever seems to ever match, even regexps which work as intended with String.search() and/or very simple (and largely useless) regexps like /abc/g.
I have tried regexps directly in the statement:
txt = txt.replaceAll(/abc/g, 'cba');
defined previously as a literal:
var re = /abc/g;
txt = txt.replaceAll(re, 'cba');
or with the constructor:
var re = new RegExp('abc', 'g');
txt = txt.replaceAll(re, 'cba');
None of these does anything: txt is never altered. I have also tried without the global flag with no difference. This happens both within scripts and in the immediate interpreter. If the same regexp is used with String.search(re) it works as expected.
On the other hand, using String.replace() with a regular expression I get the following error:
org.eclipse.ease.ScriptExecutionException: SyntaxError: The choice of Java method java.lang.String.replace matching JavaScript argument types (function,string) is ambiguous; candidate methods are:
class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence)
class java.lang.String replace(char,char)
What am I doing wrong?
|
|
|
|
|
Re: Regexp in String.replaceAll() not working? [message #1847010 is a reply to message #1846994] |
Tue, 12 October 2021 02:38  |
Eclipse User |
|
|
|
Hi,
in Rhino you may have as well JavaScript Strings as Java Strings. What type you get depends on the source that creates the string. These 2 String types are a permanent source of confusion and failing scripts. Therefore I recommend to convert Strings to dedicated objects:
var anyString = ....;
var javaScriptString = anyString + "";
var javaString = new java.lang.String(anyString);
HTH
Christian
|
|
|
Powered by
FUDForum. Page generated in 0.03279 seconds