我正在尝试使用正则表达式从“line”字符串中获取两个玩家值并将它们插入到 player1 和 player2 中。 try (BufferedReader in = new BufferedReader(new FileReader(file))) { String line; String player1; String player2; while ((line = in.readLine()) != null) { Scanner input = new Scanner(line); input.useDelimiter("(.* [a-z] )|\\sby "); if(line.toLowerCase().contains("kill")) { kill += 1; //i would like to set the player1 and player2 here } } }我的文件片段(.txt): 13:37 Kill: 3 4 7: Oootsimo killed Dono da Bola by MOD_ROCKET_SPLASH 13:37 Item: 5 weapon_rocketlauncher 13:39 Item: 6 weapon_rocketlauncher 13:40 Item: 7 ammo_rockets 13:41 Item: 6 weapon_rocketlauncher 13:41 Item: 4 weapon_rocketlauncher 13:43 Kill: 2 5 6: Isgalamido killed Assasinu Credi by MOD_ROCKET 13:45 Kill: 1022 7 22: <world> killed Mal by MOD_TRIGGER_HURT 13:46 Kill: 4 3 7: Dono da Bola killed Oootsimo by MOD_ROCKET_SPLASH 13:46 Kill: 6 2 6: Zeh killed Isgalamido by MOD_ROCKET
1 回答
BIG阳
TA贡献1859条经验 获得超6个赞
我不知道您的所有要求,但请尝试使用 Regexp:
@Test
public void test()
{
String string = "13:46 Kill: 6 2 6: Zeh killed Isgalamido by MOD_ROCKET";
String regexp = "\\d+:\\d+ .*?([A-Za-z0-9]+) killed ([A-Za-z0-9]+).*?";
String player1 = null;
String player2 = null;
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(string);
if (m.find())
{
player1 = m.group(1);
player2 = m.group(2);
}
assertEquals("Zeh", player1);
assertEquals("Isgalamido", player2);
}
说明:\d+ - 一个数字,一次或多次
.* - 任意字符,任意次数。这 '?' 表示“非贪婪”,因此匹配以下表达式的字符不会被覆盖
([A-Za-z0-9]+) - '[]' 内的字符范围,一次或多次,被捕获
一旦我确认这是你的意思,我会再次编辑我的答案
添加回答
举报
0/150
提交
取消