【问题标题】:Java - Extract everything between [* ... *]Java - 提取 [* ... *] 之间的所有内容
【发布时间】:2023-04-03 14:13:01
【问题描述】:

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

[* content I want *] 
[ more content ]

我想阅读该文件并能够提取content I want。我能做的最好的就是在下面,但它会返回

[ more content ]

请注意,content I wantmore 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;
}

【问题讨论】:

  • 注意完全是骗子,但同样的事情:stackoverflow.com/questions/13174624/…
  • 使用匹配器和查找而不是扫描仪。
  • 如果您的内容可以包含括号,为什么要排除它们? [^]]+那部分不应该是.+吗?
  • 这个\[\* (.+) \*\]有什么问题
  • 我还想补充一点,您可能会发现站点debuggex.com 对正则表达式问题很有用。您可以在其中粘贴一个正则表达式,它会直观地向您显示匹配的内容。

标签: java regex parsing


【解决方案1】:

下面的正则表达式应该可以工作:

\[\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

【讨论】:

  • 这是不对的。如果使用 OP 的示例输入,它匹配“我想要的内容”和“更多内容”,但 OP 只想要“我想要的内容”
  • @ezig 哦,现在我明白了。
猜你喜欢
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
相关资源
最近更新 更多