java - 修改动态输入字符串

标签 java regex

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

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/

相关文章:

java - 当我们编写自定义反序列化器时,如何使用 Jackson 反序列化对象数组

regex - grails的任何BDD框架(spock/geb/easyb/other)是否支持人类可读描述的正则表达式解析?

javascript - 如何将 'aA1' 或 'Aa1' 或 '1aA' 与正则表达式匹配?

java - 无法在 Intellij for Java 项目中构建或运行测试

java - Talend 的两个版本给出不同的结果

java - 使用许多连续图像时如何修复 java 堆空间内存不足

java - 是否有理由总是使用对象而不是基元?

php - 如何测试输入字段是否包含外来字符?

python - 需要帮助解析 Cisco 输出

ruby - 匹配未转义的平衡定界符对