有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java字符串将错误与正则表达式匹配

我必须拆分一个字符串,如果它的格式如下

String test="City: East Khasi Hills";

有时我可能会

如果在“:”之后有任何单词,我想匹配模式

我在用

String city=test.matches(":(.*)")?test.split(":")[1].trim():"";

但我的正则表达式返回错误。厌倦了用regex online tool测试字符串的方式进行调试

我在工具中找到了匹配项。但java给了我错误的回答


共 (2) 个答案

  1. # 1 楼答案

    你并不真的需要两个匹配项和split两者。只需像这样使用split

    String[] arr = "City: East Khasi Hills".split("\\s*:\\s*");
    String city = arr.length==2 ? arr[1] : "";
    //=> "East Khasi Hills"
    
  2. # 2 楼答案

    首先,我认为你需要检查你的整体模式是否符合预期。所以,你可以试试这样:

    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());
    }