String str = "#aaa# #bbb# #ccc# #ddd#"
谁能告诉我如何使用常规获取子字符串“aaa”,“bbb”,“ccc”,“ddd”(“##”对中的子字符串,“##”的数量未知)表达?
谢谢!
使用正则表达式:
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]
试试这个:
String str = "1aaa2 3bbb4 5ccc6 7ddd8";
String[] data = str.split("[\\d ]+");
结果数组中的每个位置都将包含一个子字符串,但第一个为空的除外:
System.out.println(Arrays.toString(data));
> [, aaa, bbb, ccc, ddd]
这是另一种使用方法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());