Java工具:字符串轉化爲表達式進行判斷

1.場景:判斷某個字符串匹配未知長度List<String>字符串集合,(1.遍歷。2.組裝表達式)

         我傾向於後者

public static void main(String[] args) {
		List<String> list=new ArrayList<String>();
		list.add("123");
		list.add("456");
		String express = getExpress(list);
		System.out.println(judge(express,"123"));
		
	}
//表達式和某字符串比較
public static boolean judge(String express, String node) {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		engine.put("node", node);
		Object result = null;
		try {
			result = engine.eval(express);
		} catch (ScriptException e) {
			log.error("字符串轉化運算表達式出錯", e);
		}
		return (boolean) result;
	}
//獲取表達式
public static String getExpress(List<String> listStr) {
		if (listStr.size() == 1) {
			String str = "(node.equals(\"" + listStr.get(0) + "\"))";
			return str;
		}
		String str = "(";
		for (int i = 0; i < listStr.size(); i++) {
			if (i == 0) {
				str = str + "node.equals(\"" + listStr.get(i) + "\")";
				continue;
			}
			if (i == listStr.size() - 1) {
				str = str + "||node.equals(\"" + listStr.get(i) + "\"))";
				continue;
			}
			str = str + "||node.equals(\"" + listStr.get(i) + "\")";
		}
		return str;
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章