Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式无法匹配行首的空格_Java_Regex - Fatal编程技术网

Java 正则表达式无法匹配行首的空格

Java 正则表达式无法匹配行首的空格,java,regex,Java,Regex,我有以下单元测试来检查XML行开头的缩进: private static final String REGEX_PATTERN = "^\\s+"; @BeforeTest @Parameters("unformattedXmlFile") public void setup(String unformattedXmlFile) throws TransformerException, ParserConfigurationException, InstantiationException,

我有以下单元测试来检查XML行开头的缩进:

private static final String REGEX_PATTERN = "^\\s+";

@BeforeTest
@Parameters("unformattedXmlFile")
public void setup(String unformattedXmlFile) throws TransformerException, ParserConfigurationException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    EditXmlPanel panel = new EditXmlPanel();
    try {
        String unformatted = readFile(unformattedXmlFile);
        String formatter = panel.prettyFormat(unformatted);         
        String [] lines = formatter.split("\n");

        for(int i=0; i < lines.length; i++) {
            System.out.println(lines[i]);
            if(i !=0 && i !=lines.length -1) {                  
                //Assert.assertEquals((Character.isWhitespace(lines[i].charAt(0))), true);
                Assert.assertEquals(lines[i].matches(REGEX_PATTERN), true);
            }
        }           

    } catch (IOException e) {
        Assert.fail("Unable to read file: " + e.getMessage(), e);
    }

}
因此,在行的开始处匹配任意数量的空格。我已经使用regexr.com检查了这个模式,看起来还可以,但是断言总是失败。我不明白为什么。

您的正则表达式必须是:

private static final String REGEX_PATTERN = "\\s+.*";
因为
String.matches
尝试将整行与正则表达式匹配,否则返回false


PS:由于同样的原因,您不需要在正则表达式中使用锚定
^
$

在语句中:
行[i]。匹配(正则表达式模式)
您正在匹配的
^\\s+
与整个

因此,要么您的行由所有空格组成,要么您的断言将失败

您可以使用
模式
/
匹配器
习惯用法,也可以调用
String.matches,使用更广泛的模式匹配整个行


请参阅
String#matches
API

您的正则表达式不应该匹配整行,包括索引后的部分吗?澄清一点:Assert.assertEquals首先取预期值,实际值第二,所以应该是“Assert.assertEquals(true,lines[i].matches(regex_模式));”。。。当然,您也可以使用assertTrue.Javadoc,我的assertEquals是:
void org.testng.Assert.assertEquals(布尔实际值,布尔预期值)
-我使用的是testng,它与junit相反。。。这就是:
void org.junit.Assert.assertEquals(预期对象,实际对象)
——必须说这有点让人困惑。
^\\s+
private static final String REGEX_PATTERN = "\\s+.*";