package com.smtscript.lib.regex; import java.util.regex.Matcher; import org.mozilla.javascript.Context; import org.mozilla.javascript.NativeFunction; import org.mozilla.javascript.Wrapper; public class JSRegexMatcher { protected JSRegex _parentRegex; protected Matcher _matcher; public JSRegexMatcher(JSRegex jsRegex, Matcher matcher) { _parentRegex = jsRegex; _matcher = matcher; } public boolean find() { return _matcher.find(); } public String group(int index) { return _matcher.group(index); } public int start(int group) { return _matcher.start(group); } public int end(int group) { return _matcher.end(group); } public String replace(Object replace) throws Exception { if(replace instanceof Wrapper) replace = ((Wrapper)replace).unwrap(); if(replace instanceof String) { return _matcher.replaceAll((String)replace); } else if(replace instanceof NativeFunction) { Context cx = _parentRegex.__parentScope__().__runtime__().entryContext(); try { Object[] args = new Object[]{this}; StringBuffer sb = new StringBuffer(); while (_matcher.find()) { Object value = ((NativeFunction)replace).call(cx, ((NativeFunction)replace), null, args); _matcher.appendReplacement(sb, value.toString()); } _matcher.appendTail(sb); return sb.toString(); } finally { Context.exit(); } } else throw new Exception("unsupport replace type : " + replace.getClass().getName()); } }