gpt4 book ai didi

Java - 提取 [* ... *] 之间的所有内容

转载 作者:行者123 更新时间:2023-12-01 22:09:29 27 4
gpt4 key购买 nike

我有一个如下所示的文本文件:

[* content I want *] 
[ more content ]

我想读取该文件并能够提取我想要的内容。我能做的最好的事情如下,但它会返回

[更多内容]

请注意,我想要的内容更多内容都包含方括号和圆括号,但它们从不包含[**] .

public static String parseFile(String src) throws IOException
{
String s = "";
File f = new File(src);
Scanner sc = new Scanner(f);
sc.useDelimiter("\\[\\*([^]]+)\\*\\]");
s= sc.next();
sc.close();
return s;
}

最佳答案

以下正则表达式应该有效:

\[\s*\*\s*(.*?)\s*?\*\s*\]

https://regex101.com/r/uC4lH9/3

你可以像这样使用它(Java 8):

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {
public static final Pattern PATTERN = Pattern.compile("\\[\\s*\\*\\s*(.*?)\\s*?\\*\\s*\\]");

public static List<String> parse(String fileContent) {
Matcher matcher = PATTERN.matcher(fileContent);
List<String> foundData = new ArrayList<>();
while (matcher.find()) {
foundData.add(matcher.group(1));
}
return foundData;
}

public static void printOutList(List<? extends CharSequence> list) {
list.forEach(System.out::println);
}

public static void main(String[] args) {
printOutList(parse("[ this will not match ] [ * YOU WILL BE MATCHED!!!11 * ] [* you as well *] [*you too*]" +
" [ * this as well *] [this * will * not]"));
}
}

输出:

YOU WILL BE MATCHED!!!11
you as well
you too
this as well

你自己看看:https://ideone.com/ldclWA

关于Java - 提取 [* ... *] 之间的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32125736/

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