我有一个文本文件,其中包含
等值[GetLeagueStandingsResultDto(team = Celtic,teamId = 54,play = 28,playingAtHome = 14,playingAway = 14,won = 19,draw = 7,lost = 2,numberOfShots = 691,yellowCards = 32,redCards = 1, goalsFor = 56,goalsAgainst = 18,goalDifference = 38,points = 64,leagueName = null,season = null,id = 54),
GetLeagueStandingsResultDto(team = Rangers,teamId = 49,play = 29,playingAtHome = 14,playingAway = 15,won = 18,draw = 4,lost = 7,numberOfShots = 507,yellowCards = 46,redCards = 4,goalsFor = 59,goalAgainst = 32,goalDifference = 27,points = 58,leagueName = null,season = null,id = 49)
我想要做的是抓住每个团队goalsFor
号并将它们放入单独的变量中。
有人能把我推向正确的方向吗?
答案 0 :(得分:0)
所以基本上你想读取每一行并用正则表达式进行分析,例如
public T2 CreateSome<T2>()
where T2 : SomeBaseClass<int, T2>, new()
{
return new T2();
}
答案 1 :(得分:0)
从字符串中获取所需值的最简单方法可能是使用正则表达式模式。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String fileName = "table.txt";
FileReader fr = null;
try {
fr = new FileReader(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(fr);
String line = "";
try {
if ((line = reader.readLine()) != null) {
// Match and capture the values we are looking for
Pattern pattern = Pattern.compile("team=(\\w+),[\\w\\s,=]+goalsFor=(\\d+),");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
// Output the results, you could store them in a
// variable instead
System.out.println("Team name: " + matcher.group(1) +
". Goals for: " + matcher.group(2));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
正则表达式模式team=(\\w+),[\\w\\s,=]+goalsFor=(\\d+),
执行以下操作:
team=(\\w+),
完全匹配team=
,然后在捕获组中匹配任何字母数字字符\w
一次或多次+
,然后匹配字符{{1} } ,
匹配任何字母数字字符[\\w\\s,=]+
,任何空格\w
\s
字符或,
字符,因为量词{一次或多次{ {1}},它会在找到字符=
时停止匹配。您可以替换+
,匹配除)
字符以外的任何内容。[^\)]+
的匹配项,此模式与捕获组中的字符)
后跟一个或多个数字完全匹配,后跟a,而不是必要的goalsFor=(\\d+),
字符。此模式将导致每个团队一个匹配,团队名称存储在第一个捕获组中,目标数量存储在第二个捕获组中。
如果你想了解更多有关正则表达式或自己进行实验的信息,可以在线获得很好的文档,几乎每种编程语言都有一个专门用于正则表达式的文档部分,还有一些 playgrounds 使用起来既方便又有趣,我使用Regexr但必须有数百个。