我有一个读取文件的方法,将每个单词放入一个字符串数组中,然后将每个单词添加到树中。我想修改它,以便如果它包含非英语字符,例如西班牙语等,则不会将该词添加到树中。我虽然关于'contains'方法,但它不适用于String类型的数组。我该怎么办?
public void parse(File f) throws Exception {
Node root = new Node('+'); //create a root node
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line;
while((line = br.readLine())!=null){
String[] words = line.toLowerCase().split(" ");
for(int i = 0; i < words.length; i++){
addToTree(words[i], root);
}
}//end of while
答案 0 :(得分:3)
您可以使用正则表达式:
Pattern nonEng = Pattern.compile("[^A-Za-z]");
...
for(int i = 0; i < words.length; i++) {
if (!pattern.matcher(words[i]).find()) {
addToTree(words[i], root);
}
}
这会丢弃所有不完全由英文字符组成的单词。
答案 1 :(得分:0)
如果单词由[a-zA-Z_0-9]
中的字母组成return !myString.matches("^\\w+$");
如果您有标点符号和其他字符等特殊要求,请在正则表达式中添加它们。 [^ \ W。,;:'“]