我有一个字符串 String l =“姓名:kumar 年龄:22 关系:单例” 它是从 UI 动态发送的,现在我需要将上面的字符串拆分为
name: kumar
age: 22
relationship: single
我的代码是:
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 );
}
}
如有任何建议,我们将不胜感激,谢谢
最佳答案
您可以使用此正则表达式:
\S+\s*:\s*\S+
或者这个:
\w+\s*:\s*\w+
演示:https://regex101.com/r/EgXlcD/6
正则表达式:
\S+
- 1 个或多个非空格字符
\s*
- 0 个或多个空格字符
\w+
- 0 个或多个 \w
即 [A-Za-z0-9_]
个字符。
关于java - 正则表达式在冒号上分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42105789/