繁体   English   中英

在Java中使用正则表达式查找纯文本中的值。

[英]Using regex in java to find values in plain text.

我有一个与之交谈的服务器,该服务器使用纯文本命令和响应。 样本响应如下所示

COMMENT: Monitor Version 2.2.1 
REQUIRE: IDENT
WAITING: 

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

RESPONSE: COMMANDSENT ARG1 ARG2 ... ARGN

我想使用regex查找字符串COMMANDSENT以及到达ARGN的结果参数。 我不确定该怎么做。

我将表达式读为“如果字符串包含“ RESPONSE”,则搜索“:”并返回空格之间的每个标记,直到遇到换行符为止”。 使用正则表达式可能吗?

我已经找到了很多指南,但是开始却很艰巨,有人可以给我一些如何开始的指导,有用的表达方式会有所帮助吗?

也许您可以执行String.split("RESPONSE") ,然后再次在结果数组上的空格/分号上进行分割?

正则表达式在我的经验中有点令人讨厌。

尝试这个

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

我认为split是最好的方法。 但是,由于您不熟悉正则表达式,因此以下是使用正则表达式的示例。 我正在对您的要求做一些假设。

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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM