Distributed today, how to ensure that the front end of the regular and back-end always maintain the same, has been a puzzle to everyone.

The solution here: Use a javascript engine

1. How to determine whether a regular expression is valid

The Java language side calls the javascript engine

	public static boolean isRegex(String regex) {
		var ret = false;
		javax.script.ScriptEngineManager se = new javax.script.ScriptEngineManager();
		javax.script.ScriptEngine engine = se.getEngineByName("js");
		
		engine.put("rgx", regex);
		try {
			ret = (boolean) engine.eval(
				    "var isreg; try{isreg=eval(rgx) instanceof RegExp}catch(e){isreg=false}");
		} catch (ScriptException e) {
			ret = false;
		}
		return ret;
	}
Copy the code

2. How to use regular expressions to verify input

The Java language side calls the javascript engine

	public static boolean matches(String regex,String val) {
		
		var value = false;
		
		javax.script.ScriptEngineManager se = new javax.script.ScriptEngineManager();
		javax.script.ScriptEngine engine = se.getEngineByName("js");
		
		String regExp = regex;
		engine.put("str", val);

		try {
			
			engine.eval("var rgx=" + regExp);
			value = (boolean) engine.eval(
				    "function validate(r, s){ return (r).test(s); }; validate(rgx, str);");
			
			return value;
			
		} catch (ScriptException e) {
			throw newPatternSyntaxException(e.getMessage(),regex,e.getLineNumber()); }}Copy the code