【问题标题】:How to preserve delimeters while using String.split() in Java?在 Java 中使用 String.split() 时如何保留分隔符?
【发布时间】:2016-09-02 05:59:31
【问题描述】:
String TextValue = "hello{MyVar} Discover {MyVar2} {MyVar3}";
String[] splitString = TextValue.split("\\{*\\}");

我得到的输出是[{MyVar, {MyVar2, {MyVar3] in splitString

但我的要求是保留那些分隔符{},即[{MyVar}, {MyVar2}, {MyVar3}]

需要一种方法来匹配上述输出。

【问题讨论】:

标签: java


【解决方案1】:

使用类似的东西:

Pattern p = Pattern.compile("(\\{\\w+\\})");
String str = ...
Matcher m = p.matcher(str);
while(m.find())
    System.out.println(m.group(1));

请注意,上面的代码未经测试,但它会在大括号内查找单词并将它们放在一个组中。然后它将遍历字符串并输出任何与上面的表达式匹配的字符串。

here 提供了一个正则表达式示例。

【讨论】:

    【解决方案2】:

    感谢 kelvin 和 npinti。

    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    
    public class CreateMatcherExample {
        public static void main(String[] args) {
            String TextValue = "hello{MyVar} Discover {My_Var2} {My_Var3}";
            String patternString = "\\{\\w+\\}";
    
            Pattern pattern = Pattern.compile(patternString);
            Matcher matcher = pattern.matcher(TextValue);
    
            while(matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
    

    【讨论】:

    • 2 次要注意事项:如果答案解决了您的问题,则将该答案标记为正确,通常仅在您最终得到与提供的答案不同的结果时才建议发布您的解决方案。其次,您使用的代码是通过表达式打印匹配项。虽然这可行,但如果您向表达式中添加更多您不希望在最终结果中包含的内容,它就会中断。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2013-02-23
    • 2011-02-14
    相关资源
    最近更新 更多