正则表达式匹配文本字符串内的文本与删除尾随换行符

时间:2011-08-06 17:30:55

标签: java regex

您好我需要找到能够获得本文中间部分的正则表达式:

# Command // first line with symbol character 

First line of interest
Second line of interest
\n
Third line of interest
\n
\n // I am not interested in trailing new lines.

我怎样才能获得以第一行感兴趣并结束第三行感兴趣的文本?谢谢。

3 个答案:

答案 0 :(得分:3)

您提供的示例非常基本,我希望您可以将此正则表达式转移到您的用例:

((?mi)First.*interest\b)

说明:

(
(?mi)    // Use DOTALL and MULTILINE mode
First    // First word you are interested in
.*       // Any character...
interest // ..up to the last word you are interested in
\b       // Word boundary to stop there
)

如果(?mi)不起作用,请使用java.util.regex.Pattern中记录的标志。

要使用正则表达式,最好让一位编辑向您展示正则表达式匹配的内容,例如:http://myregexp.com/signedJar.html

答案 1 :(得分:3)

String test = "# Command\n\nFirst line of interest\r\nSecond line of interest\n\r\nThird line of interest\r\n\n";
System.out.printf("%n>>%s<<%n", test);

Pattern p = Pattern.compile("^(?!#).+(?:[\r\n]+.+)*", Pattern.MULTILINE);
Matcher m = p.matcher(test);
if (m.find())
{
  System.out.printf("%n>>%s<<%n", m.group());
}

输出:

>># Command

First line of interest
Second line of interest

Third line of interest

<<

>>First line of interest
Second line of interest

Third line of interest<<

匹配从第一行的开头(^开始)(不是以哈希符号(?!#)开头),但 包含字符除了行分隔符(.+ .*)。

[\r\n]+匹配一个或多个行分隔符,无论它们是Unix(\n),DOS(\r\n)还是旧版Mac(\r)样式分隔器。无论您的代码运行在什么平台上,您都应该随时准备好处理任何或所有不同的行分隔符。

然后,

(?:[\r\n]+.+)*匹配零个或多个其他行,而不匹配任何尾随行分隔符。

答案 2 :(得分:0)

使用

Pattern.compile("(?<=# Command\\n\\n)[^\\n].*[^\\n](?=\\n*)", Pattern.DOTALL)

我不确定感兴趣的线条之前的文字是多么的文字,所以我硬编码了积极的外观。您可以根据需要进行修改。

相关问题