November 1, 2012

Extacting words between $ symbol

Question by rajesh

I want to extract the words between the symbol $.

String = " this is first attribute $color$. this is the second attribute $size$"

I want to get a string list as List =[color , size]

I have used

Pattern pattern = Pattern.compile("(\$) .* (\$)");
Matcher matcher = pattern.matcher(sentence);

but I get the out put as

"$color$.this is the second attribute $size$"

please help me to solve this problem

Answer by halex

The problem is that the regex you are using is greedy and consumes everything beginning at the first $ until the last $ in your string. You have to add a ? after the * to make the regex nongreedy:

Pattern pattern = Pattern.compile("\$(.*?)\$");
Matcher matcher = pattern.matcher(sentence);
List<String> result = new ArrayList<String>();
for(int i=1; i <= matcher.groupCount(); i++)
    result.add(matcher.group(i);

Answer by Starx

Try this regex. It should give what is expected.

Pattern pattern = Pattern.compile("$(.*?)$");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!