gpt4 book ai didi

java - java从字符串中提取子字符串

转载 作者:行者123 更新时间:2023-12-02 13:33:09 27 4
gpt4 key购买 nike

我想从字符串中提取特定的子字符串:

String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+
"info2 info2ContentA";

结果应该是:

String info1 ="info1ContentA info1ContentB";
String info2 ="info2ContentA";
String info3 ="info3ContentA info3ContentB";

对我来说,提取信息非常困难,因为有时“info”后面是一个、两个或多个内容信息。出现的另一个问题是,info1、info2 等的顺序未排序,并且“真实数据”不包含升序数字。

我的第一个想法是将 info1、info2、info3 等添加到 ArrayList。

private ArrayList<String> arr = new ArrayList<String>();
arr.add("info1");
arr.add("info2");
arr.add("info3");

现在我想使用 Apache Commons ( https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4 ) 中的 StringUtils.substringBetween() 方法提取子字符串:

String result = StringUtils.substringBetween(source, arr.get(0), arr.get(1));

如果 info1 位于 info2 之前的字符串中,则此方法有效,但就像我所说的“真实数据”未排序。

知道如何解决这个问题吗?

最佳答案

按空格分割这些字符串 然后使用String的方法startsWith将部分添加到正确的结果字符串

Map<String, String> resultMap = new HashMap<String, String>();
String[] prefixes = new String[]{"info1", "info2", "info3"};
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+" info2 info2ContentA";
String[] parts = source.split(" ");

for(String part : parts) {
for(String prefix : prefixes) {
if(part.startsWith(prefix) {
String currentResult = (resultMap.containsKey(prefix) ? resultMap.get(prefix) + part + " " : part);
resultMap.put(prefix, currentResult);
}
}
}

还可以考虑使用StringBuilder而不是添加字符串部分

<小时/>

如果您不能确定部件是否会包含空格,您可以在开始时更改所有 part<SPACE>part在源字符串中使用 String replace方法

关于java - java从字符串中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43112791/

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