我會開始標記爲「單詞」,拆分*/+ - ()^和空格。如果我明白你在做什麼,結果應該只是數字。
要使用番石榴分割: 可重複令牌= Splitter.on(CharMatcher.anyOf(「 - /*+(){")).split(myExpression);
然後你就可以掃描 「字」 尋找一個小數點由@Scary袋熊的建議
下面是一個完整的版本:
public void test() {
char[] values = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
List<Character> ints = Chars.asList(values);
String str = "the values are 4 and 4.03 tons";
Iterable<String> tokens = Splitter.on(CharMatcher.anyOf("- /*+()^")).split(str);
for (String token : tokens) {
char[] chars = token.toCharArray();
for (char c : chars) {
if (!ints.contains(c)) {
System.out.println(token + " is not an int");
break;
}
}
}
}
生產:
the is not an int
values is not an int
are is not an int
and is not an int
4.03 is not an int
tons is not an int
如果(表達式。 contains(「。」)) – 2015-03-19 00:36:59
表達式是否只有數字,其他字符如()+ *,對不對?或錯誤的輸入(字母)也? – RahulArackal 2015-03-19 00:45:43
要評估包括數學運算的數值表達式,請嘗試使用ScriptEngine類,如綠色箭頭所示,請參閱http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java。要使用Java來評估它,會涉及到編寫一個將它執行到外部文件的類,然後編譯並將其jar作爲外部可執行文件運行。 – 2015-03-19 01:07:22