[英]Read from text file with a condition
我正在讀取一個文本文件,其條件是以*開頭的單詞將被忽略。
example:
abc 1234 *text to be ignored
所以在這個例子中,當從文本文件中讀取時,我將忽略“要忽略的文本”,並且只將字節數組中的abc和1234存儲起來。
為此,我寫了下面的代碼。 如何實現忽略以*開頭的單詞的條件?
public static void read(String filename) {
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader (new FileReader(filename));
while ((line = reader.readLine()) != null) {
String[] functionName = line.split("\\s+");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果String以給定的字符串文字開頭,則startWith(String literal)
返回true。
例如 :
"1234".startsWith("12");
返回true
。
因此,您應該閱讀所有單詞並檢查它是否開始甚至包含*,如果是,則忽略整個單詞。
示例:
if(! word.startsWith("*")) {
// add to what ever you want
}
要么
if(! word.contains("*")) {
// add to what ever you want
}
您可以嘗試使用substring()
類的indexOf()
while ((line = reader.readLine()) != null) {
if(line.indexOf("*")>-1)
line=line.substring(0,line.indexOf("*"));
String[] functionName = line.split("\\s+");
}
上面的indexOf("*")
會給你*
的索引然后你可以通過執行substring(beginIndex,endIndex)
找到帶有endIndex
的子字符串作為indexOf("*")
找到的*
的索引
你可以在你的while循環中做一些事情 -
while ((line = reader.readLine()) != null) {
String[] functionName = line.split("\\s+");
String newLine = "";
for(String strg : functionName){
if(strg.startsWith("*")){
break;
}else{
newLine = strg + newLine;
}
}
}
你不知道你正在使用什么版本的Java,所以我將假設Java 8 ......
注意:代碼未經測試,但它應該適用於一些調整。
private static final Pattern SPACES = Pattern.compile("\\s+");
private static final Pattern STAR_TO_END = Pattern.compile("\\s*\\*.*");
public static String[] read(final String filename)
{
final Path path = Paths.get(filename);
try (
// UTF-8 by default; excellent
final Stream<String> lines = Files.line(path);
) {
return lines.map(line -> STAR_TO_END.matcher(line).replaceFirst(""))
.flatMap(SPACES::splitAsStream)
.collect(Collectors.toArray(String[]::new));
}
}
如果你不想循環翻閱你的單詞以檢查它是否以*
開頭,你也可以在使用split
之前刪除所有帶星號的單詞。
String str = "abc 1234 *text to be ignored";
System.out.println(Arrays.toString(str.replaceAll("\\*[^\\s]+\\s*", "").split("\\s+")));
// [abc, 1234, to, be, ignored]
str = "*abc *1234 *text to be *ignored";
System.out.println(Arrays.toString(str.replaceAll("\\*[^\\s]+\\s*", "").split("\\s+")));
// [to, be]
正則表達式崩潰
\\* - Literal match of asterisk
[^\\s]+ - Match anything but a space
\\s* - Capture any or no spaces at end of word
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.