3

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

String test="City: East Khasi Hills";

and some times i may get String test="City:";

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

I am using

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

But my regex is returning false. tired of debugging by the way i am using regex online tool to test my string.

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

3
  • Don't use Regex101 for Java. It doesn't support the Java flavor of regex. Test with RegexPlanet instead. Commented Jul 18, 2015 at 9:40
  • Also, how do you split the String in the first place, and why? Commented Jul 18, 2015 at 9:41
  • i need to get the word after ":", if there is words else empty string Commented Jul 18, 2015 at 10:14

2 Answers 2

4

You don't really 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"
Sign up to request clarification or add additional context in comments.

5 Comments

This answer will still work by giving you text after :\s* in arr[1]
For what input it didn't work and what was your expected result?
if i have string like "city: " , in this case split won't work
Split will surely work and you will get an empty value in arr[1]. Once again what is your expected result for this input?
0

First of all, I think you need to check if your overall pattern matches 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());
}

1 Comment

my question is what if doesn't matches the pattern, any way it got resolved thanks for your time @Fernando

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.