如何从给定字符串中获取描述中的预期输出

时间:2018-05-09 04:27:17

标签: java regex string

[得分]:Bot-16从[演员 - 杀戮]获得2.0赏金[受害者:演员200_(演员_Local_Minion_200)] [@ 152133]

如何格式化上面的字符串,以便得到以下输出:

玩家ID = Bot-16

积分= 2.0

动作= [Actor-Kill]

受害者= Actor200_(Actor_Local_Minion_200)

时间戳= 152133

还有一些行没有受害者标记,如下面的字符串

[得分]:2 Dev 158744780获得20.0赏金[演员 - 杀人] [王牌] [@ 519382]

输出应为

玩家ID = 2 Dev 158744780

积分= 20.0

动作=演员杀人

受害者=王牌

时间戳= 519382

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式来处理此问题。

查看输入字符串,我已经提出了这个正则表达式:

\[Scoring\]: (.*) got ([^\s]*) bounty from \[([^\]]*)\] \[(?:Victim: )?([^\]]*)\] \[@([^\]]*)\]

DEMO HERE:https://regex101.com/r/e3zuKw/2

所以这是Java中的演示程序及其输出。我认为这将是你的解决方案。

输出:

**First Input**
Player-ID = Bot-16
Points = 2.0
Action = Actor - Kill
Victim = Actor200_(Actor_Local_Minion_200)
Timestamp = 152133

**Second Input**
Player-ID = 2 Dev 158744780
Points = 20.0
Action = Actor - Kill
Victim = Ace
Timestamp = 519382

代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {
    public static void main(String[] args) {
        System.out.println("**First Input**");
        printInfo("[Scoring]: Bot-16 got 2.0 bounty from [Actor - Kill] [Victim: Actor200_(Actor_Local_Minion_200)] [@152133]");

        System.out.println("\n**Second Input**");
        printInfo("[Scoring]: 2 Dev 158744780 got 20.0 bounty from [Actor - Kill] [Ace] [@519382]");
    }

    public static void printInfo(String line) {
        String pattern = "\\[Scoring\\]: (.*) got ([^\\s]*) bounty from \\[([^\\]]*)\\] \\[(?:Victim: )?([^\\]]*)\\] \\[@([^\\]]*)\\]";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(line);

        if (m.find()) {
            System.out.println("Player-ID = " + m.group(1));
            System.out.println("Points = " + m.group(2));
            System.out.println("Action = " + m.group(3));
            System.out.println("Victim = " + m.group(4));
            System.out.println("Timestamp = " + m.group(5));
        }
    }
}