我正在使用Java實現詞法分析器。 Inside「String palavras_reservadas」我有所有保留字不能用來命名變量和類似的東西。匹配器負責在我的輸入代碼中查找這些保留字。 我把我輸入代碼中的所有行放在一個名爲「vetor1」的ArrayList的不同位置。 我想在找到一個保留字時拆分這個「vetor1」。例如,我有這樣的代碼爲我輸入:在Java中使用分割
a = b + c;
if (a > b)
c = c + b;
我的代碼就會把每一行的陣列的不同位置:
v[0] = a = b + c;
v[1] = if (a > b)
v[2] = c = c + b;
我想要做的是:
v[0] = a = b + c;
v[1] = if
v[2] = (a > b)
v[3] = c = c + b;
(或類似的東西)。我可以使用split來做到這一點嗎?
這是我到目前爲止有:
public class AnalisadorLexico {
public static void main(String args[]) throws FileNotFoundException {
List<String> vetor1 = new ArrayList<String>();
File text = new File("/Users/Mvaguimaraes/Desktop/codigo.marcos");
Scanner scnr = new Scanner(text);
String palavras_reservadas = "fim-se|enquanto|então|se|senão|para|de|até|faça|fim-para|fim-enquanto";
Pattern r = Pattern.compile(palavras_reservadas);
int i = 0;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
vetor1.add(line);
Matcher m = r.matcher(scnr.nextLine());
if (m.find()) {
System.out.println("Found value: " + m.group());
}
}
for(i = 0; i<vetor1.size(); i++)
{
String value = vetor1.get(i);
System.out.println(value);
}
}
}
是否有任何其他方法可以在不使用拆分的情況下執行此操作? – 2015-03-24 22:09:54
你可以通過使用正則表達式或者string.substring(0,3).equals(「if」)來檢查關鍵字(比如if),然後像下面這樣用substring手動分割它們:假設你在列表中的位置是k你做list.set(k,string.substring(0,3))和list.add(k + 1,string.substring(3,string.length) – Dix 2015-03-24 22:15:41
在「m.group()」我有字符串拆分序列。那麼,如何使用它來在代碼中分割vetor1? – 2015-03-24 22:52:09