[英]How to extract a string after and before a specific word using Java regular expression
I need to extract a string after opResult
and before another string (word+ '=') 我需要在
opResult
之后和另一个字符串之前提取一个字符串(word +'=')
For example: 例如:
testest=false opResult=Critical extension not supported random=abc srcPort=10
testest = false opResult =不支持关键扩展random = abc srcPort = 10
So I should extract out Critical extension not supported
, before the next word with an equals sign. 因此,我应该在下一个带有等号的单词之前提取出
Critical extension not supported
。
Also, it should also work if there is no other string at the back, meaning I should get the same result with the below example. 另外,如果后面没有其他字符串,它也应该起作用,这意味着下面的示例应该得到相同的结果。
typesOnly=false opResult=Critical extension not supported
typesOnly = false opResult =不支持关键扩展
The regular expression I have currently extracted everything before the last '=' sign. 我目前正则表达式提取了最后一个'='符号之前的所有内容。
opResult=(\S.*)(\s\w+=)
We can try matching/extracting using the following pattern: 我们可以尝试使用以下模式进行匹配/提取:
.*opResult=(.*?)(?:\\s*\\S+=.*|$)
The trick here is in being able to articulate when the next key begins, and then to not extract it. 这里的技巧是能够清楚地表达下一个键何时开始,然后不提取它。
String line = "testest=false opResult=Critical extension not supported random=abc srcPort=10";
String pattern = ".*opResult=(.*?)(?:\\s*\\S+=.*|$)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println(m.group(1));
}
Output: 输出:
Critical extension not supported
Demo here: 演示在这里:
We need to find text after 'opResult=' before the next blankspace(\\s)word(\\w+) followed by an equals sign (?==) and whatever follows (.*) 我们需要在“ opResult =”之后的下一个空格(\\ s)word(\\ w +)之前找到文本,后跟等号(?==)和后面的任何内容(。*)
Pattern becomes 模式变成
.*opResult=([\w|\s]+)(\s\w+(?==).*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.