Java string matches error with REGEX

I need to split a String if it has this format below

String test="City: East Khasi Hills";

      

and several times I can get String test="City:";

I want to match a pattern if there are any words after the ":",

I use

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

      

But my regex is returning false. tired of debugging btw i am using online regex tool to validate my string.

I am getting a match in the tool. but java returns me false.

+3


source to share


2 answers


You don't need both matches and split

both. Just use split

like this:



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

      

+4


source


First of all, I think you need to check if your overall pattern is as expected. So, you can try something like this:



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

      

0


source







All Articles