简体   繁体   English

使用FileUtils时出错

[英]Error while using FileUtils

I am using FileUtils from apache commons.io to search text between two strings in a file with the following code: 我正在使用来自apache commons.io的FileUtils,使用以下代码在文件中两个字符串之间搜索文本:

Pattern p = Pattern.compile(Pattern.quote(fromDate) + "(.*?)" + Pattern.quote(toDate));

try {
    Matcher m = p.matcher(fileContent);                  
    while (m.find()) {
        System.out.println(m.group(1));

But there is an error it is giving output only when both the strings lie in same line, no output if strings are in at different lines? 但是有一个错误,那就是仅当两个字符串都位于同一行时才给出输出,如果字符串位于不同的行时就没有输出? Here i am taking the content of whole file into a Sting Varibale "fileContent". 在这里,我将整个文件的内容放入Sting Varibale的“ fileContent”中。

The dot won't search over multiple lines. 点将不会搜索多行。 You need to give a second parameter for this Pattern.DOTALL like so: Pattern p = Pattern.compile(Pattern.quote(fromDate) + "(.*?)" + Pattern.quote(toDate), Pattern.DOTALL); 您需要像这样给这个Pattern.DOTALL提供第二个参数: Pattern p = Pattern.compile(Pattern.quote(fromDate) + "(.*?)" + Pattern.quote(toDate), Pattern.DOTALL);

Also this topics has some good explanation how it works: Match multiline text using regular expression 此外,本主题还对它的工作原理进行了很好的解释: 使用正则表达式匹配多行文本

try ending the regex with ?s so you new regex should be: "(.*?s)" 尝试以?s结尾的正则表达式,因此新的正则表达式应为:“(。*?s)”

In most case the matcher stops evaluate expression when it encounters a line feed \\n. 在大多数情况下,匹配器在遇到换行符\\ n时会停止计算表达式。 ?s make the matcher pass the \\n when it try to match the regex. 使匹配器在尝试匹配正则表达式时通过\\ n。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM