简体   繁体   English

在Java 7中使用正则表达式使用换行符查找模式

[英]Finding pattern with newline using regex in Java 7

I am writing a regular expression being used to search through files and find the following pattern: 我正在写一个正则表达式,用于搜索文件并查找以下模式:

{@link ClassName} provides
 *

I have written this expression so far using java.util.regex.Pattern : 到目前为止,我已经使用java.util.regex.Pattern编写了此表达式:

private static final Pattern MY_PATTERN =
        Pattern.compile("\\{@link [a-zA-Z0-9]*\\} provides\r\n \\*");

However, this is not finding any matches. 但是,这找不到任何匹配项。 I have got as far as finding the pattern without the newline, but trying to search for the pattern with the newline and '*' character is proving difficult. 我已经找到了没有换行符的模式,但是尝试搜索带有换行符和'*'字符的模式非常困难。

How else can I check if there is a newline followed by a '*'? 我还要如何检查是否有换行符后跟'*'? I've also tried '\\r' and '\\n' on their own in the pattern. 我也已经在模式中尝试了“ \\ r”和“ \\ n”。

Note: I'm using Java version 1.7.0_25 注意:我正在使用Java版本1.7.0_25

Update Showing my code (left out the bit where I print out the matches to console): 更新显示我的代码(在我将要打印的内容打印到控制台的位置上省略了一点):

public class PatternSearcher
{
    private static final String JAVA_FILES_GLOB = "glob:**/*.java";
    private static final Pattern MY_PATTERN =
        Pattern.compile("\\{@link [a-zA-Z0-9]*\\} provides\r\n \\*");

    @Test
    public void checkForPattern() throws Exception
    {
        final StringBuilder filesWithPattern = new StringBuilder();

        final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(JAVA_FILES_GLOB);

        Files.walkFileTree(SourceCodeTestUtil.getErsCoreDir().toPath(), new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException
            {
                if (pathMatcher.matches(file))
                {
                    for (final String line : Files.readAllLines(file, Charset.defaultCharset()))
                    {
                        if (MY_PATTERN.matcher(line).find())
                        {
                            filesWithPattern.append(file).append("\n");
                        }
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

您可以尝试以下模式

"\\{@link \\w+\\} provides\\n \\*"

It works with this: 它适用于此:

private static final Pattern MY_PATTERN =
        Pattern.compile("\\{@link [a-zA-Z0-9]*\\} provides(\\r|\\n|\\r\\n) \\*");

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

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