[英]Java Scanner Class Help
我想了解如何使用掃描儀從輸入文件中打印某個字符串。 對於要打印的字符串,該行必須以* star開頭,並且該字符串必須用引號引起來,並且是下一個標記,並且與* star在同一行,而忽略空白。
示例輸入文本文件:“ test.txt”
這是一個測驗
*星級“ variableX”
更多測試
*星級“ variableY
多得多
測試
*星級下一個“ variableZ”
基於此樣本輸入文本,輸出應僅為。
“variableX”
這是我的代碼的一部分:
Scanner scanner = new Scanner (new File ("test.txt"));
while (scanner.hasNextLine()){
if(scanner.hasNext("*star")) {
scanner.next();
if(scanner.hasNext()){
String test = scanner.next();
System.out.println(test);
}
但是它缺少一些關鍵的東西。 非常感謝幫助!
package so3947761;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private static final Pattern RELEVANT_LINE_PATTERN =
Pattern.compile("^\\*star\\s+\"(.*)\"$");
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("test.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Matcher m = RELEVANT_LINE_PATTERN.matcher(line);
if (m.matches()) {
String data = m.group(1);
System.out.println(data);
}
}
}
}
一些評論:
\\n
),則不能通過正則表達式來完成,因此必須顯式定義要替換的序列。 ^
的右側(行的開頭)和$
的左側(行的末尾)添加\\\\s*
。 while (scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.startsWith("*star")){
String[] split= line.split("\\s+"); //Split the string where there is whitespace
//No whitespace after *star
if ((split.length<2)){
System.exit(0);
}
String file= split[1];
String star=split[0];
String file1=file.trim(); //Removes whitespace
if(file1.startsWith("\"")&&(file1.endsWith("\""))){
System.out.println(file1);
}
}
這可以解決問題
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner (new File ("c:\\test.txt"));
while (scanner.hasNextLine()){
if(scanner.hasNext(Pattern.compile("\\*star"))) {
scanner.next();
System.out.println(scanner.nextLine());
return;
}
else
scanner.nextLine();
}
}
編輯:答案中缺少引號部分,即使沒有輸出,我也記不住要放它,但這是一個更可靠的解決方案:
Scanner scanner = new Scanner (new File ("c:\\new.txt"));
while (scanner.hasNextLine()){
if(scanner.hasNext(Pattern.compile("\\*star"))) {
scanner.next();
String s = scanner.nextLine();
Matcher m = Pattern.compile("\".+\"").matcher(s);
if(m.find())
{
System.out.println(m.group());
return;
}
}
else
scanner.nextLine();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.