user3229532
user3229532

Reputation: 27

Extracting symbols from string with regex

I have a String in such format ${something} and want to extract something using regular expressions in Java. Here is my code:

String tmp = null; 
Pattern pVars = Pattern.compile("\\$\\{([^}]*)\\}");
Matcher mVars = pVars.matcher(vars[0]);
if (mVars.find())
{
         tmp = mVars.group();
}

But I get full String in this case.

Upvotes: 1

Views: 57

Answers (2)

maxdev
maxdev

Reputation: 2566

Use group(1) to access the inner group demarked by () in your expression.

Upvotes: 1

M A
M A

Reputation: 72854

You are still extracting the whole pattern instead of the group inside parentheses. This is how group behaves when it has no parameters.

Specify the first capturing group by passing 1 as parameter:

tmp = mVars.group(1);

Upvotes: 3

Related Questions