試しにやってみた的な。
@Test public void test_js_regexp() throws Exception { String text = lines( "line 1: ", "line 2: <foo>foo_content</foo>", "line 3: " ); String fooContent = getByRegExp( text, lines( " text.match(/<foo>(.+?)<\\/foo>/); ", " result = RegExp.$1; " ) ); assertThat(fooContent, is("foo_content")); } // text と result は決め打ち private String getByRegExp(String text, String code) throws ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.put("text", text); engine.eval(code); return (String) engine.get("result"); } private String lines(String... strings) { String text = ""; for (String it : strings) { text += it + "\n"; } return text; }