Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p> I have a idea about custom string replacement in Java. Not as easy as replacement function in JavaScript but it just works fine. Here is the code: </p> <pre><code> package org.eve.util; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils{ public static String replaceWithFn(CharSequence input,String regexp,Method fn,int group){ Matcher m=Pattern.compile(regexp).matcher(input); StringBuffer sb=new StringBuffer(); try { Object obj=Modifier.toString(fn.getModifiers()).indexOf("static")&gt;-1? fn.getClass():fn.getDeclaringClass().newInstance(); if(fn.getReturnType()!=String.class){ System.out.println("replacement function must return type \"String\"."); } while(m.find()){ m.appendReplacement(sb, (String)fn.invoke(obj, m.group(group))); } m.appendTail(sb); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } } </code></pre> <p>&nbsp;</p> <p><code><pre> package org.eve.test;</p> <pre><code>import org.eve.util.StringUtils; public class ReplaceTest { public static void main(String[] args) { try { StringBuffer input=new StringBuffer("\\u039D\\u03B9\\u03BA\\u03CC\\u03BB\\u03B1\\u03BF\\u03C2 Nicholas \\u5C3C\\u53E4\\u62C9\\u65AF"); System.out.println("input="+input); String result=StringUtils.replaceWithFn( input, "\\\\u([0-9a-zA-Z]{4})", ReplaceTest.class.getMethod("hex2char",String.class), 1 ); System.out.println("output="+result); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } public String hex2char(String s){ //TODO replaceholder return String.valueOf((char)Integer.parseInt(s,16)); } } </code></pre> <p></code></pre></p> <p> Just for fun. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload