[英]Substring between lines using Regular Expression Java
Hi I am having following string 嗨,我有以下字符串
abc test ...
interface
somedata ...
xxx ...
!
sdfff as ##
example
yyy sdd @# .
!
I have a requirement that I want to find content between a line having word "interface" or "example" and a line "!". 我有一个要求,我想在具有单词“ interface”或“ example”的行与“!”行之间找到内容。
Required output will be something like below 所需的输出如下所示
String[] output= {"somedata ...\nxxx ...\n","yyy sdd @# .\n"} ;
I can do this manually using substring and iteration . 我可以使用substring和eration手动进行此操作。 But I want to achieve this using regular expression. 但是我想使用正则表达式来实现。 Is it possible? 可能吗?
This is what I have tried 这就是我尝试过的
String sample="abc\ninterface\nsomedata\nxxx\n!\nsdfff\ninterface\nyyy\n!\n";
Pattern pattern = Pattern.compile("(?m)\ninterface(.*?)\n!\n");
Matcher m =pattern.matcher(sample);
while (m.find()) {
System.out.println(m.group());
}
Am I Right? 我对吗? Please suggest a right way of doing it . 请提出正确的做法。
Edit : 编辑:
A small change : I want to find content between a line "interface" or "example" and a line "!". 一个小变化:我想在“接口”或“示例”行与“!”行之间找到内容。
Can we achieve this too using regex ? 我们也可以使用正则表达式来实现吗?
You could use (?s)
DOTALL modifier. 您可以使用(?s)
DOTALL修饰符。
String sample="abc\ninterface\nsomedata\nxxx\n!\nsdfff\ninterface\nyyy\n!\n";
Pattern pattern = Pattern.compile("(?s)(?<=\\ninterface\\n).*?(?=\\n!\\n)");//Pattern.compile("(?m)^.*$");
Matcher m =pattern.matcher(sample);
while (m.find()) {
System.out.println(m.group());
}
Output: 输出:
somedata
xxx
yyy
Note that the input in your example is different. 请注意,示例中的输入是不同的。
(?<=\\\\ninterface\\\\n)
Asserts that the match must be preceded by the characters which are matched by the pattern present inside the positive lookbehind. (?<=\\\\ninterface\\\\n)
断言匹配必须以与正向后方内部存在的模式匹配的字符为开头。
(?=\\\\n!\\\\n)
Asserts that the match must be followed by the characters which are matched by the pattern present inside the positive lookahead. (?=\\\\n!\\\\n)
断言必须在匹配项后跟与正向超前查询中存在的模式匹配的字符。
Update: 更新:
Pattern pattern = Pattern.compile("(?s)(?<=\\n(?:example|interface)\\n).*?(?=\\n!\\n)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.