There are times in development where it is necessary to intercept a value in a string followed by a variable, and to do a simple operation on this value, such as "Tom, age, come fron us", here to determine whether or not older than 30 years old, to achieve the following:
1String inputstr = "Tom, age, come fron us";2String matchstring = "Age variable 1";//variable regular expressions that need to be intercepted3String rulestring = "Variable 1 > 30";//formulas For comparison4 5 //1, use regular expression to intercept the age value6String Paramregex = "(Variable [0-9]{1,})"; 7Pattern Patternfetchparams =Pattern.compile (Paramregex);8Matcher Matcherfetchparams =Patternfetchparams.matcher (matchstring);9 TenString paramname =NULL;//get variable name: Variable 1 One if(Matcherfetchparams.find ()) { AParamName = Matcherfetchparams.group (1); - } -System.out.println ("paramname:" + paramname);//paramname: Variable 1 the -String Ruleregex = Matchstring.replaceall ("(Variable [0-9]{1,})", "(\\\\s*)"); -Pattern pattern =Pattern.compile (Ruleregex); -Matcher Matcher =Pattern.matcher (INPUTSTR); +String paramvalue =NULL;//Get variable Value: - if(Matcher.find ()) { +Paramvalue = Matcher.group (1); AParamvalue = Paramvalue.replace (",", "" "); at } -System.out.println ("paramvalue:" + paramvalue);//paramvalue:23 - - //1. Use JavaScript engine to determine whether the formula is satisfied -Scriptenginemanager Manager =NewScriptenginemanager (); -ScriptEngine engine = Manager.getenginebyname ("javascript"); in engine.put (paramname, paramvalue); - to Booleanresult =(Boolean) engine.eval (rulestring); +SYSTEM.OUT.PRINTLN ("Result:" + result);//Result:false
Java reads a variable value in a string and makes a simple comparison