我與UVa #494玩分裂的話,我設法與下面的代碼來解決這個問題:弗吉尼亞#494 - 正則表達式[^ A-ZA-Z] +使用Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Main {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = in.readLine()) != null){
String words[] = line.split("[^a-zA-z]+");
int cnt = words.length;
// for some reason it is counting two words for 234234ddfdfd and words[0] is empty
if(cnt != 0 && words[0].isEmpty()) cnt--; // ugly fix, if has words and the first is empty, reduce one word
System.out.println(cnt);
}
System.exit(0);
}
}
我建的正則表達式"[^a-zA-z]+"
分詞,例如字符串abc..abc
或abc432abc
應該拆分爲["abc", "abc"]
。但是,當我嘗試使用字符串432abc
時,我的結果是["", "abc"]
- words[]
中的第一個元素只是一個空字符串,但我期望只有["abc"]
。我無法弄清楚爲什麼這個正則表達式給了我第一個元素""
這種情況。