String str = "#aaa# #bbb# #ccc# #ddd#"
有人能告诉我怎样才能得到子字符串“aaa”,“bbb”,“ccc”,“ddd”(子字符串在“##”对中,而“##”的数字是未知的)使用正则表达式?
谢谢!
答案 0 :(得分:3)
使用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]
答案 1 :(得分:2)
试试这个:
String str = "1aaa2 3bbb4 5ccc6 7ddd8";
String[] data = str.split("[\\d ]+");
结果数组中的每个位置都将包含一个子字符串,除了第一个空字符串:
System.out.println(Arrays.toString(data));
> [, aaa, bbb, ccc, ddd]
答案 2 :(得分:-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());