[英]How to parse string with Java?
我正在嘗試制作一個簡單的計算器應用程序,該應用程序將采用這樣的字符串
5 + 4 + 3 - 2 - 10 + 15
我需要Java將此字符串解析為數組
{5, +4, +3, -2, -10, +15}
假設用戶可以在每個數字和每個運算符之間輸入0或多個空格
我是Java的新手,所以我不確定如何完成此工作。
您可以使用Integer.parseInt來獲取值,分割可以使用String類實現的字符串。 正則表達式可以工作,但我不知道該怎么做:3
看一下String.split() :
String str = "1 + 2";
System.out.println(java.util.Arrays.toString(str.split(" ")));
[1,+,2]
請注意,split使用正則表達式,因此您必須用雙引號將字符分隔。 或具有特殊含義的類似字符。 同樣,一行中的多個空格將在解析數組中創建您需要跳過的空字符串。
這解決了簡單的示例。 為了更嚴格地解析真實表達式,您需要創建一個語法並使用諸如Antlr之類的東西。
令str
為行緩沖區。
將Regex.match用於模式([-+]?[ \\t]*[0-9]+)
。
將所有匹配項累積到String[] tokens
。
然后,對於每個token
在tokens
:
String s[] = tokens[i].split(" +");
if (s.length > 1)
tokens[i] = s[0] + s[1];
else
tokens[i] = s[0];
您可以使用正向后面:
String s = "5 + 4 + 3 - 2 - 10 + 15";
Pattern p = Pattern.compile("(?<=[0-9]) +");
String[] result = p.split(s);
for(String ss : result)
System.out.println(ss.replaceAll(" ", ""));
String cal = "5 + 4 + 3 - 2 - 10 + 15";
//matches combinations of '+' or '-', whitespace, number
Pattern pat = Pattern.compile("[-+]{1}\\s*\\d+");
Matcher mat = pat.matcher(cal);
List<String> ops = new ArrayList<String>();
while(mat.find())
{
ops.add(mat.group());
}
//gets first number and puts in beginning of List
ops.add(0, cal.substring(0, cal.indexOf(" ")));
for(int i = 0; i < ops.size(); i++)
{
//remove whitespace
ops.set(i, ops.get(i).replaceAll("\\s*", ""));
}
System.out.println(Arrays.toString(ops.toArray()));
//[5, +4, +3, -2, -10, +15]
根據一些答案的輸入,我發現這是最好的解決方案
// input
String s = "5 + 4 + 3 - 2 - 10 + 15";
ArrayList<Integer> numbers = new ArrayList<Integer>();
// remove whitespace
s = s.replaceAll("\\s+", "");
// parse string
Pattern pattern = Pattern.compile("[-]?\\d+");
Matcher matcher = pattern.matcher(s);
// add numbers to array
while (matcher.find()) {
numbers.add(Integer.parseInt(matcher.group()));
}
// numbers
// {5, 4, 3, -2, -10, 15}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.