gpt4 book ai didi

java - 提取嵌套大括号内的数据

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:33:24 27 4
gpt4 key购买 nike

我想分别提取第一个嵌套大括号和第二个嵌套大括号之间的内容。现在我完全坚持这个任何人都可以帮助我。我的文件 read.txt 包含以下数据。我只是把它读成一个字符串“s”。

  BufferedReader br=new BufferedReader(new FileReader("read.txt"));
while(br.ready())
{
String s=br.readLine();
System.out.println(s);

}

输出

{ { "John", "ran" },                { "NOUN", "VERB" } },
{ { "The", "dog", "jumped"}, { "DET", "NOUN", "VERB" } },
{ { "Mike","lives","in","Poland"}, {"NOUN","VERB","DET","NOUN"} },

即我的输出应该是这样的

  "John", "ran"    
"NOUN", "VERB"
"The", "dog", "jumped"
"DET", "NOUN", "VERB"
"Mike","lives","in","Poland"
"NOUN","VERB","DET","NOUN"

最佳答案

使用这个正则表达式:

(?<=\{)(?!\s*\{)[^{}]+

查看 Regex Demo 中的匹配项.

在 Java 中:

Pattern regex = Pattern.compile("(?<=\\{)(?!\\s*\\{)[^{}]+");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// matched text: regexMatcher.group()
}

解释

  • 回顾 (?<=\{)断言当前位置之前的是 {
  • 负前瞻 (?!\s*\{)断言后面的内容不是可选空格然后 {
  • [^{}]+匹配任何不是 curl 的字符

关于java - 提取嵌套大括号内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25029925/

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