Java RegEx SubString多行之间

时间:2015-09-04 11:15:50

标签: java regex substring

我有以下内容。

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));
}

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

2 个答案:

答案 0 :(得分: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),它仍然有效。

答案 1 :(得分:1)

你需要再次转义所有\,因为java字符串,但也像stribizhev所说,如果你想匹配\\那么你需要\\\\在正则表达式但是java regex中的(?m)c\\\\cert\\\\\\s"(\\w++)"\\stext\\s((?:.+\\n)+(?:.+))

你可能想要更像这样的东西:

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

所以这部分((?:.+\\n)+(?:.+))在引号中有什么意义,主要是你的东西只是java-ified

这一点 MethodInvocation: MethodName ( [ArgumentList] ) TypeName . [TypeArguments] Identifier ( [ArgumentList] ) ExpressionName . [TypeArguments] Identifier ( [ArgumentList] ) Primary . [TypeArguments] Identifier ( [ArgumentList] ) super . [TypeArguments] Identifier ( [ArgumentList] ) TypeName . super . [TypeArguments] Identifier ( [ArgumentList] ) 将捕获任意数量的至少包含1个字符的行