简体   繁体   English

正则表达式在冒号上拆分字符串

[英]Regular expression split string on colon

I have a string String l = "name: kumar age: 22 relationship: single " it is comming from UI dynamically now i need to split the above string to 我有一个字符串String l =“ name:kumar age:22关系:single”它是从UI动态生成的,现在我需要将上述字符串拆分为

name: kumar
age: 22 
relationship: single

My code is : 我的代码是:

Pattern ptn = Pattern.compile("([^\\s]+( ?= ?[^\\s]*)?)");
    Matcher mt = ptn.matcher(l);
    while(mt.find())
    {
        String col_dat=mt.group(0);
        if(col_dat !=null && col_dat.length()>0)
        {
            System.out.println("\t"+col_dat );
        }
    }

Any Suggestions will appreciated Thank you 任何建议将不胜感激谢谢

You can use this regex: 您可以使用此正则表达式:

\S+\s*:\s*\S+

Or this: 或这个:

\w+\s*:\s*\w+

Demo: https://regex101.com/r/EgXlcD/6 演示: https//regex101.com/r/EgXlcD/6

Regex: 正则表达式:

\\S+ - 1 or more non space characters \\S+ -1个或多个非空格字符

\\s* - 0 or more space characters \\s* -0个或更多空格字符

\\w+ - 0 or more \\w ie [A-Za-z0-9_] characters. \\w+ -0或更多\\w[A-Za-z0-9_]字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM