[英]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.