繁体   English   中英

Java RegEx SubString多行之间

[英]Java RegEx SubString Between multiple lines

我有如下内容。

c\cert\ "test1" text
--Begin Cert
cert content1
cert content 2
--End Cert

c\cert\ "testCert2" text
--Begin Cert
cert test content1
cert test content 2
--End Cert

c\cert\ "sampleCert2" text
--Begin Cert
sample content1
sample test content 2
--End Cert

我需要提取内容并保存在类似的地图中

Key:test1
value:"--Begin Cert
    cert content1
    cert content 2
    --End Cert"
Key:testCert2
value:"--Begin Cert
    cert test content1
    cert test content 2
    --End Cert"
. 
.
etc

我可以逐行循环。 但是我想用RegEx做到这一点。 这就是我尝试过的。

Matcher m = Pattern.compile("(?m)^c\\\\cert\\\\ \"(\\w++)\" text\r?\n(.*?)\\s*$").matcher(configContent)
while (m.find()) {
map.put(m.group(1),m.group(2));
}

但是我没有得到预期的输出。 请帮助我形成正确的正则表达式。

下面的代码可以做到这一点:

Pattern p = Pattern.compile("^c\\\\cert\\\\ \"([^\"]+)\" text\r?\n" +
                            "(--Begin Cert\r?\n.*?\r?\n--End Cert)[\r\n]*",
                            Pattern.MULTILINE | Pattern.DOTALL);
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.println("Key:" + m.group(1));
    System.out.println("value:\"" + m.group(2) + "\"");
    System.out.println();
}

运行:

String input = "c\\cert\\ \"test1\" text\r\n" +
               "--Begin Cert\r\n" +
               "cert content1\r\n" +
               "cert content 2\r\n" +
               "--End Cert\r\n" +
               "\r\n" +
               "c\\cert\\ \"testCert2\" text\r\n" +
               "--Begin Cert\r\n" +
               "cert test content1\r\n" +
               "cert test content 2\r\n" +
               "--End Cert\r\n" +
               "\r\n" +
               "c\\cert\\ \"sampleCert2\" text\r\n" +
               "--Begin Cert\r\n" +
               "sample content1\r\n" +
               "sample test content 2\r\n" +
               "--End Cert\r\n";

你会得到:

Key:test1
value:"--Begin Cert
cert content1
cert content 2
--End Cert"

Key:testCert2
value:"--Begin Cert
cert test content1
cert test content 2
--End Cert"

Key:sampleCert2
value:"--Begin Cert
sample content1
sample test content 2
--End Cert"

仅将输入更改为换行符( \\n代替\\r\\n ),它仍然可以工作。

您需要再次转义所有\\ ,因为java字符串,但是也像stribizhev所说的,如果要匹配\\则在正则表达式中需要\\\\但在Java regex中需要\\\\\\\\

您可能想要更多这样的东西:

(?m)c\\\\\\\\cert\\\\\\\\\\\\s"(\\\\w++)"\\\\stext\\\\s((?:.+\\\\n)+(?:.+))

因此,这部分(?m)c\\\\\\\\cert\\\\\\\\\\\\s"(\\\\w++)"\\\\stext\\\\s会得到引号,主要是Java修饰的东西

并且此位((?:.+\\\\n)+(?:.+))将捕获至少1个字符的任意行

暂无
暂无

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

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