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("$(.*?)$");