1
String str = "#aaa# #bbb# #ccc#   #ddd#"

谁能告诉我如何使用常规获取子字符串“aaa”,“bbb”,“ccc”,“ddd”(“##”对中的子字符串,“##”的数量未知)表达?

谢谢!

4

3 回答 3

3

使用正则表达式

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]

http://ideone.com/i1IAZ

于 2012-05-01T03:21:10.890 回答
2

试试这个:

String str = "1aaa2 3bbb4 5ccc6   7ddd8";
String[] data = str.split("[\\d ]+");

结果数组中的每个位置都将包含一个子字符串,但第一个为空的除外:

System.out.println(Arrays.toString(data));
> [, aaa, bbb, ccc, ddd]
于 2012-05-01T03:14:20.930 回答
-1

这是另一种使用方法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());
于 2012-05-01T03:54:12.063 回答