gpt4 book ai didi

java - 使用 Java 从字符串中提取标记

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:37 25 4
gpt4 key购买 nike

我正在编写一个 Java 程序来从字符串中提取标记,如下所示:“我的名字是 ${lastName},${firstName}。”

我的预期输出是一个数组我的名字是${lastName}${firstName}.

我编写了一个静态方法来执行此操作:

static List<String> tokenize(String str) {
List<String> results = new ArrayList<String>();

int idx = -1;
int beginIndex = 0;
while ((idx = str.indexOf("${")) > -1) {
results.add(str.substring(beginIndex, idx));
str = str.substring(idx + 2);

idx = str.indexOf("}");
if (idx > 0) {
results.add("${" + str.substring(0, idx) + "}");
str = str.substring(idx + 1);
}
}
results.add(str);
return results;
}

但是,我想知道是否有任何开源库可以达到相同的结果。

最佳答案

您可以使用正则表达式来分割

String[] data = input.split("(?=\\$)")

它将以此格式(数组)返回您的数据。

[My name is , ${lastName}, , ${firstName}]

将其转换为列表

List<String> list = Arrays.asList(array);

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

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