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!
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]
(\\w+) to ([\\w\\s]+) or ([^#]+)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]
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());
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." docs.oracle.com/javase/7/docs/api/java/util/…