![](/img/trans.png)
[英][Json][Java] Clueless into how to parse this text. Using a library
[英]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.