我有一个如下所示的文本文件:
[* 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
关于Java - 提取 [* ... *] 之间的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32125736/