Reputation: 59
I have a string like this.
//Locaton;RowIndex;maxRows=New York, NY_10007;1;4
From this i need to get the contry name New York only. How it can possible in a single step code.
i used..
String str = "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 ";
str = str.split("=")[1];
str = str.split(",")[0]
the above code contails lots of splits.How can i avoid thiis. i want to get the contry name only using single code.
Upvotes: 1
Views: 87
Reputation: 34424
Use capture groups with regex which perfect capturing the specific data from string.
String str = "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 ";
String pattern = "(.*?=)(.*?)(,.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
if (m.find()) {
System.out.println("Group 1: " + m.group(1));
System.out.println("Group 2: " + m.group(2));
System.out.println("Group 3: " + m.group(3));
}
Here is the output
Group 1: Locaton;RowIndex;maxRows=
Group 2: New York
Group 3: , NY_10007;1;4
Upvotes: 1
Reputation: 8387
Try to use this regular expression "=(.*?),"
like this:
String str = "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 ";
Pattern pattern = Pattern.compile("=(.*?),");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
Output:
New York
Using
matcher.group(1)
means capturing groups make it easy to extract part of the regex match,parentheses also create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses.
Match "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 "
Group 1: "New York"
Upvotes: 4