简体   繁体   中英

how to get substring using regular expression in java?

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]

http://ideone.com/i1IAZ

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM