简体   繁体   English

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

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

I have a server that I am speaking with that speaks with plain text commands and responses. 我有一个与之交谈的服务器,该服务器使用纯文本命令和响应。 A sample response looks like 样本响应如下所示

COMMENT: Monitor Version 2.2.1 
REQUIRE: IDENT
WAITING: 

I would like to use regular expressions to find information in the responses. 我想使用正则表达式在响应中查找信息。 At some points on line of the response might look like 在某些时候,响应可能看起来像

RESPONSE: COMMANDSENT ARG1 ARG2 ... ARGN

I would like to use regex to find the string COMMANDSENT along with the resulting arguments up to ARGN . 我想使用regex查找字符串COMMANDSENT以及到达ARGN的结果参数。 I am not sure how to do this. 我不确定该怎么做。

I would have the expression read "If the string contains "RESPONSE" search for a ":" and return each token between spaces until a newline is encountered". 我将表达式读为“如果字符串包含“ RESPONSE”,则搜索“:”并返回空格之间的每个标记,直到遇到换行符为止”。 Is this possible with regular expressions? 使用正则表达式可能吗?

I have found quite a few guides but it is quite daunting to start, could someone give me some pointers on how to start on this, useful expressions that would help? 我已经找到了很多指南,但是开始却很艰巨,有人可以给我一些如何开始的指导,有用的表达方式会有所帮助吗?

Perhaps you can do a String.split("RESPONSE") and then again split on spaces/colons on the resulting array? 也许您可以执行String.split("RESPONSE") ,然后再次在结果数组上的空格/分号上进行分割?

Regex is a bit nasty in my experience. 正则表达式在我的经验中有点令人讨厌。

尝试这个

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

I think split is the best way to go here. 我认为split是最好的方法。 However, since you're new to regexes, here's an example of how it could be done with regexes. 但是,由于您不熟悉正则表达式,因此以下是使用正则表达式的示例。 I'm making some assumptions about what your requirements are. 我正在对您的要求做一些假设。

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