使用小于(<)符号时,Java RegEx不匹配

Inf*_*ero 0 java regex

我试图在Java中使用这个RegEx: 在以下代码中:

public class Intervals {
public static void main( String[] args ) {
    try {
        FileReader fr = new FileReader( new File( "ex11.intervals.txt"));

        BufferedReader br = new BufferedReader( fr );

        while( br.read() != -1 ){
            String currentLine = new String( br.readLine() );

            Pattern p = Pattern.compile( "<hr( +size *= *[0-9]+)? *>" );

            Matcher m = p.matcher( currentLine );

            while( m.find() ){
                System.out.println( currentLine );
            }
        }

    } catch( FileNotFoundException fne ){
        fne.printStackTrace();
    } catch( IOException e ){
        e.printStackTrace();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用,但如果我使用egrep UNIX实用程序执行它,它可以正常工作.

ex11.intervals.txt内容:

<hr>
<hr >
<hr size=15>
<hr size =    21 >
Run Code Online (Sandbox Code Playgroud)

有人知道这件事发生了什么?

我试过了

Pattern p = Pattern.compile( "<hr>" )
Run Code Online (Sandbox Code Playgroud)

但都不起作用.

有什么建议,帮忙吗?

提前致谢

din*_*dev 7

更改您的代码以读取文件,如下所示:

String currentLine = null;

while( (currentLine = br.readLine()) != null ){

}
Run Code Online (Sandbox Code Playgroud)

当你这样做时,read()你总是阅读第一个字符,从而跳过你的HTML标签中的少于签名.

  • 此外,将Pattern.compile(...)语句移出循环并重用它. (2认同)