yvetterowe
yvetterowe

Reputation: 1279

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!

Upvotes: 1

Views: 993

Answers (3)

coderplus
coderplus

Reputation: 5913

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

Upvotes: -1

Matt Ball
Matt Ball

Reputation: 360016

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

Upvotes: 3

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236140

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]

Upvotes: 2

Related Questions