1
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!

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

yeah that works=). Would you please explain to me what does "w+" mean in the regex? Thanks =)
It's standard regex syntax. Read the JavaDocs linked in my answer. If those aren't clear enough, acquaint yourself with regular-expressions.info.
hmm if i change the input String into "#aaa# #bbb bbb# #ccc# #ddd#", then the parts will be [aaa,null,ccc,ddd]. Can you figure out a more general way that "bbb bbb"(there is a space between the words in the substring) can also be output? Thanks a lot =D
Change (\\w+) to ([\\w\\s]+) or ([^#]+)
2

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]

1 Comment

... or something like that. As with so many questions on regexes, the OP has not CLEARLY specified his/her requirements.
-1

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

2 Comments

-1. "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." docs.oracle.com/javase/7/docs/api/java/util/…
ok. I see your point. Though it's available in Java 7(docs.oracle.com/javase/7/docs/api/java/util/…), this class won't be available in future releases? got my answer in your comment update :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.