Reputation: 15876
Given the following string:
423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
I would like to split it and put the contents in a array excluding the square brackets and the numbers in the brackets - i.e the result should be an array that contains the following.
{423545,7568787,53654656,2021947,021947,2021947,8021947}
My attempt so far only works if there are no square brackets:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.split("(\\(\\d+\\))?(?:,|$)")
How can I update the above regex to also extract the numbers that wrapped in square brackets?
The strings I am trying to extract are identifiers for database rows so i need to extract them to retrieve the database row.
Upvotes: 0
Views: 230
Reputation: 124225
You could try this way
String str = "[342398789], [233434] ,423545(50),[7568787(500)],"
+ "53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceFirst("^\\[", "").split(
"(\\(\\d+\\))?\\]?(\\s*,\\s*\\[?|$)");
System.out.println(Arrays.toString(listItems));
output
[342398789, 233434, 423545, 7568787, 53654656, 2021947, 021947, 2021947, 8021947]
Upvotes: 2
Reputation: 595
try this way:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceAll("\\(\\d+\\)","")replaceAll("\\[","").replaceAll("\\]","").split(",");
Upvotes: 1