如果它具有以下格式
,我必须拆分一个字符串String test="City: East Khasi Hills";
有时我可能会String test="City:";
如果“:”,
之后有任何单词,我想匹配模式我正在使用
String city=test.matches(":(.*)")?test.split(":")[1].trim():"";
但我的正则表达式是假的。厌倦了我使用regex online tool测试我的字符串的方式进行调试。
我正在使用该工具进行匹配。但是java让我错了。
答案 0 :(得分:4)
你真的不需要两个匹配和split
。只需像这样使用split
:
String[] arr = "City: East Khasi Hills".split("\\s*:\\s*");
String city = arr.length==2 ? arr[1] : "";
//=> "East Khasi Hills"
答案 1 :(得分:0)
首先,我认为您需要检查整体模式是否符合预期。所以,你可以尝试这样的事情:
String str = "City: East Khasi Hills";
// Test if your pattern matches
if (str.matches("(\\w)+:(\\s(\\w)+)*")) {
// Split your string
String[] split = str.split(":");
// Get the information you need
System.out.println("Attribute name: " + split[0]);
System.out.println("Attribute value: " + split[1].trim());
}