-1

I have a string

I #have# #a# #string#

I have the regex #[^#]+# that should give strings between hash marks in this string.

I need to declare

String y = {first word surrounded by hashmarks in sentence}

Help me change the above pseudo-code into real code, please.

11
  • 1
    vogella.com/articles/JavaRegularExpressions/article.html Commented Nov 30, 2013 at 21:04
  • 2
    What pseudo-code? I only see requirements here. Commented Nov 30, 2013 at 21:04
  • 1
    You have to put more effort before asking a question and actually do sth by yourself first so that you can paste your code here. Commented Nov 30, 2013 at 21:05
  • thanks, but read through that already in my quest and didn't glean from it what i apparently should have. Commented Nov 30, 2013 at 21:05
  • 1
    First go through this docs.oracle.com/javase/tutorial/essential/regex/index.html and go back to us after you do. Of course then you may know the answer but if you do not we'll help you. Commented Nov 30, 2013 at 21:06

1 Answer 1

1
    Pattern pattern = Pattern.compile("#([^#]+)#");
    Matcher matcher = pattern.matcher("I #have# #a# #string#");
    while(matcher.find()){
        String y = matcher.group(1);
        // do something with y
    }

Explanation:

The parenthesis around [^#]+ allow to capture the content between them, and access it later by calling group(1) on the matcher. The 1 means first parenthesis group (in our example there is only one anyway).

The loop might be optional in your case. It iterates on all the words between # found in the string. If you only want the first one just call matcher.find() once with no loop.

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

4 Comments

Can you explain this code?
specifically, does matcher.group(1) refer to the first instance of the matcher?
Thanks, wouldn't the match's number be 0, though?
No, 0 is a special index returning the whole pattern, see docs.oracle.com/javase/7/docs/api/java/util/regex/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.