[英]Finding specific elements of a string read in from a .txt file in Java
[英]Finding specific text in txt file and storing it in String
首先,我想說我是初學者,這是我的第一個Java程序。 我想創建一個程序來讀取文本文件,找到特定的行,並將其保存到我的字符串變量中。
所以我想找到以“Dealt to”開頭的行,然后在那行中復制所有內容,直到這個char'['並將它放在我的字符串變量中。
所以我要說我在我的文本文件中有這一行: Dealt to My NickName [text]我想要一個程序找到文本“我的昵稱”並將它放在我的字符串變量中。
我正在嘗試使用類並嘗試使用setter和getter來練習,請讓我知道我的代碼是什么樣的,以及如何改進它並讓它工作。
這是Main.java:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
HandHistory hh1 = new HandHistory();
String hero1 = null;
hero1 = hh1.getHero();
System.out.println(hero1);
}
}
我的HandHistory.java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HandHistory {
private String hero;
public HandHistory(){}
public String getHero() throws IOException {
FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
if (line.contains("Dealt to ")){
hero = line.substring(9,(line.indexOf("["))-1);
}
}
return hero;
}
public void setHero(String hero){
this.hero = hero;
}
}
這是一個良好的開端,是逐行讀取文件的好方法。 值得修復的一個問題是使用try-finally塊關閉FileReader資源,或者從Java 7開始使用新的try-with-resources塊:
try (FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt")) {
...
}
我能想到的其他提示和評論:
我的建議是使用正則表達式。 你可以試試
(?<=beginningstringname)(.*\n?)(?=endstringname)
所以,對於你的問題,這將是
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "Dealt to My NickName [text]";
String pattern = "(?<=Dealt to )(.*\n?)(?=[)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
//m now haves what you desire. You can loop it if you want.
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
} else {
System.out.println("NO MATCH");
}
}
}
嘗試使用本教程在Java http://www.tutorialspoint.com/java/java_regular_expressions.htm中使用正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.