主题:有关正则表达式
piaoyexie
[专家分:1380] 发布于 2007-11-05 22:20:00
program ex1
const a=10;
var b,c : integer;
begin
b:=20;
c:=a+b;
end.
如何将以上代码分解成若干字母+数字(可有可无)、操作符(=、:=、+、-、*、/)和分隔符(半角标点和括号)啊?
我的思路是将操作符和分隔符替换成 空格操作符或分隔符空格
然后以空格为标记分解
可是不知道怎么实现
那位大哥提点下啊?
或是有更好的思路也行
谢谢
最后更新于:2007-11-05 22:27:00
回复列表 (共2个回复)
沙发
daifei4321 [专家分:2590] 发布于 2007-11-06 00:39:00
思路对的.
String[] ops = {"=",":=","+","-","*","/"};
String s = "program...end.";
for (String op : ops) {
s = s.replaceAll(op, " " + op + " ");
}
while (s.indexOf(" ") != -1) {
s = s.replaceAll(" ", " ");
}
String[] parts = s.split(" ");
可能会产生空字符串,用的时候检测下.要注意 := 也会被分成 : = 两部分
板凳
piaoyexie [专家分:1380] 发布于 2007-11-06 10:26:00
private static final String[] operator = { ":=", "=", "+", "-", "*", "/",
"%" };
/*
* 分隔符数组
*/
private static final String[] separator = { ",", ";", ".", "(", ")", "[",
"]", "{", "}", ":" };
............
...........
public String[] processInString(String str) {
String newStr = "";
String[] words = null;
newStr = str.replaceAll("\\:=", "#");
/*newStr = newStr.replaceAll("\\=", " = ");
newStr = newStr.replaceAll("\\+", " + ");
newStr = newStr.replaceAll("\\-", " - ");
newStr = newStr.replaceAll("\\*", " * ");
newStr = newStr.replaceAll("\\/", " / ");
newStr = newStr.replaceAll("\\%", " % ");
newStr = newStr.replaceAll("\\(", " ( ");
newStr = newStr.replaceAll("\\)", " ) ");
newStr = newStr.replaceAll("\\[", " [ ");
newStr = newStr.replaceAll("\\]", " ] ");
newStr = newStr.replaceAll("\\{", " { ");
newStr = newStr.replaceAll("\\}", " } ");*/
for(int i=1;i<operator.length;i++){
newStr=newStr.replaceAll("\\"+operator[i], " "+operator[i]+" ");
}
System.out.println(newStr);
for (int j = 0; j < separator.length; j++) {
newStr = newStr.replaceAll("\\" + separator[j], " " + separator[j]
+ " ");
}
newStr = newStr.replaceAll("\\#", " := ");
System.out.println(newStr);
words = newStr.split("\\ +");
System.out.println(newStr);
return words;
}
我用这个方法解决了
我来回复