gpt4 book ai didi

java - 如何更改正则表达式模式,以便按顺序找到每个匹配项

转载 作者:行者123 更新时间:2023-12-01 18:51:08 25 4
gpt4 key购买 nike

我有一个文本文件,其中使用以下语法存储证书:

-----BEGIN CERTIFICATE-----
Certificate is in here. It's a really long string of characters and looks like garbage. Each certificate is variable length.
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
Another certificate is in here
-----END CERTIFICATE-----

然后,我编写了代码,尝试读取上述文本文件,并一一检查每个证书。

//This copies all of my certificates from a file into a String
String certificates = new Scanner(new File("certificates.txt"), "UTF-8").useDelimiter("\\A").next();

//This creates a pattern so that I can examine each certificate one at a time
//(?s) allows this pattern to span several lines.
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE");

Matcher matcher = pattern.matcher(certificates);

//I attempt to examine each certificate one at a time
while(matcher.find())
{
System.out.println(matcher.group());
}

但是,当我调用 matcher.find() 时,它会返回整个证书文件。我认为是因为它在文件开头找到“-----BEGIN CERTIFICATE-----”,然后在文件末尾找到“-----END CERTIFICATE-----” .

如何更改我的正则表达式模式,以便它按顺序查找每个证书?

最佳答案

原因是 .*greedy匹配尽可能多的证书部分的表达式。您可以通过添加 ? 量词来使用不情愿的表达式来将此匹配限制为各个部分:

Pattern pattern = 
Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE");

关于java - 如何更改正则表达式模式,以便按顺序找到每个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com