Reputation: 1279
String str = "#aaa# #bbb# #ccc# #ddd#"
Can anybody tell me how can i get the substrings “aaa","bbb","ccc","ddd" (substring which is in the pair of "# #" and the number of "# #" is unknown) using regular expression?
Thanks!
Upvotes: 1
Views: 993
Reputation: 5913
Here is yet another way of doing it using StringTokenizer
String str="#aaa# #bbb# #ccc# #ddd#";
//# and space are the delimiters
StringTokenizer tokenizer = new StringTokenizer(str, "# ");
List<String> parts = new ArrayList<String>();
while(tokenizer.hasMoreTokens())
parts.add(tokenizer.nextToken());
Upvotes: -1
Reputation: 360016
Using regex:
Pattern p = Pattern.compile("#(\\w+)#");
String input = "#aaa# #bbb# #ccc# #ddd#";
Matcher m = p.matcher(input);
List<String> parts = new ArrayList<String>();
while (m.find())
{
parts.add(m.group(1));
}
// parts is [aaa, bbb, ccc, ddd]
Upvotes: 3
Reputation: 236140
Try this:
String str = "1aaa2 3bbb4 5ccc6 7ddd8";
String[] data = str.split("[\\d ]+");
Each position in the resulting array will contain a substring, except the first one which is empty:
System.out.println(Arrays.toString(data));
> [, aaa, bbb, ccc, ddd]
Upvotes: 2