Take the 2-minute tour ×

I am trying to use Pattern and Matcher class to extract matches out of a string.

My string is as follows: $abc$12def$def$$11$

I want to get $abc$, $def$ and $11$ from this string.

I thought of using the following regex: \$(.*)\$ (This works fine in normal pattern matching).

My java program is unable to get these. All it returns me is the entire string. Here is my program:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class dollar {

  private static String REGEX = "\\$(.*)\\$";

  private static String INPUT = "$12f$$555$button button$abc0$";

  public static void main(String[] args) {
    Pattern p = Pattern.compile(REGEX);
    boolean found = m.find();
    while (found) {
      System.out.println("TEST:" + m.start());
      System.out.println("TEST:" + m.end());
      found = m.find();

I also tried the following:


But this does not work too. How to get this done? Can it be done on jdk6 or something is available in jdk7?

Appreciate all the help!!!

share|improve this question
add comment

1 Answer

your problem is that * is greedy. Try \$(.*?)\$ instead

$abc$12def$def$$11$ = $ followed by 0 or more [anything] (which happens to be abc$12def$def$$11 in this case) followed by $

using *? makes the regex engine stop consuming characters as early as possible

share|improve this answer
Bingo that solved the issue. Gosh completely forgot about ?. Thanks and truly appreciate for the quick catch!!! –  Rahul Sep 29 '11 at 1:02
add comment

Your Answer


