在java中使用regex以纯文本格式查找值。

时间:2014-02-05 00:59:20

标签: java regex

我有一个与之交谈的服务器,它使用纯文本命令和响应。示例响应类似于

COMMENT: Monitor Version 2.2.1 
REQUIRE: IDENT
WAITING: 

我想使用正则表达式来查找响应中的信息。在响应的某些点上可能看起来像

RESPONSE: COMMANDSENT ARG1 ARG2 ... ARGN

我想使用正则表达式来查找字符串COMMANDSENT以及最终ARGN的结果参数。我不知道该怎么做。

我希望表达式为“如果字符串包含”RESPONSE“搜索”:“并在空格之间返回每个标记,直到遇到换行符”。正则表达式可以实现吗?

我已经找到了不少指南,但是开始是非常艰巨的,有人可以给我一些关于如何开始这一点的指针,有用的表达方式会有所帮助吗?

3 个答案:

答案 0 :(得分:0)

也许你可以做一个String.split("RESPONSE"),然后在结果数组上再次分割空格/冒号?

根据我的经验,正则表达式有点讨厌。

答案 1 :(得分:0)

试试这个

String[] a = s.replaceAll("(?sm).*^RESPONSE: (.*?)$.*", "$1").split(" +");

答案 2 :(得分:0)

我认为split是最好的方式。但是,由于你是regexes的新手,这里有一个如何用正则表达式完成它的例子。我对你的要求做了一些假设。

if (s.startsWith("RESPONSE:")) {
    String response = s.substring(9);  // this will take the part of the string after RESPONSE:
    Pattern pat = Pattern.compile(" *([^ ]+)");
        // the pattern is zero or more spaces, followed by one or more non-space
        // characters.  The non-space characters will be saved in a group, called
        // "group 1" since it's the first (and only) group.
    Matcher matcher = pat.matcher(response);
    ArrayList<String> args = new ArrayList<String>();
    while (matcher.find())
        args.add(matcher.group(1));
            // This repeatedly searches for the pattern, until it can't find it any
            // more.  Each time we find the pattern, we use group(1) to retrieve
            // "group 1", which is the non-space characters.  Each find() starts
            // where the previous match left off.

    // After this is done, args will contain the arguments.
}