gpt4 book ai didi

java - 修改动态输入字符串

转载 作者:行者123 更新时间:2023-11-30 10:18:56 25 4
gpt4 key购买 nike

我正在处理一项要求。我收到以下格式的输入字符串。

A:82% X 18% Y B:100% X C:82% X 18% Y AB:60% X 20% Y 20% ZZ

字符串解释,

1) String consists of multiple material names like below are the material names present in above mentioned string

A
B
C
AB

2) Every material is made up of different constituents, For example A is made from 82% of X and 18% of Y. In another input string according to material name the ratio of ingredients can split accordingly. But total is always 100%

3) A string can have multiple material names and one material can be made of n number of ingredients (Total percentage would be 100%)

我想将我的输入字符串转换为以下格式

#A:82% X,18% Y #B:100% X #C:82% X, 18% Y #AB:60% X,20% Y,20% ZZ

我可以使用正则表达式实现哈希部分,代码片段

String inp = "A:82% X 18% Y B:100% X C:82% X 18% Y AB:82% X 18% Y";
String regex = "(\\b[A-Za-z]{1,}\\:\\b)";
System.out.println(inp.replaceAll(regex, "#$1"));

但是我无法处理或不知道在特定 Material 的成分之间设置逗号。

请问有什么建议....?

最佳答案

这是一个利用 Java 8 流和正则表达式的可能解决方案。

String input = "A:82% X 18% Y B:100% X C:82% X 18% Y AB:60% X 20% Y 20% ZZ";
System.out.println(
// streaming chunks of input delimited by start of expression
Stream.of(
input.split("(?=(^| )\\p{L}+:)")
)
// mapping each chunk to replacements
.map(
s ->
// pre-pending #
s.replaceAll("(\\p{L}+:)", "#$1")
// pre-pending comma for multiple value percentages
.replaceAll("(?= \\d+% \\p{L})",",")
)
// collecting by trivial join
.collect(Collectors.joining())
);

输出

#A:82% X, 18% Y #B:100% X #C:82% X, 18% Y #AB:60% X, 20% Y, 20% ZZ

关于java - 修改动态输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48991099/

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