Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String matches error with REGEX

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.

like image 285
saikiran Avatar asked May 31 '26 00:05

saikiran


1 Answers

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"
like image 159
anubhava Avatar answered Jun 01 '26 15:06

anubhava