user3403976
user3403976

Reputation: 31

Extract a number from an amount from a String

I have below method which I use to extract amount from a string.

strAmountString = "$272.94/mo for 24 months Regular Price -$336.9"

public static String fnAmountFromString(String strAmountString) {
    String strOutput = "";

    Pattern pat = Pattern.compile("\\$(-?\\d+.\\d+)?.*");
    Matcher mat = pat.matcher(strAmountString);

    while(mat.find())
        strOutput = mat.group(1);

    return strOutput;
}

Now I have to extract string 272.94 from the string and above function works fine.

But when I have to extract 272.94 from String strAmountString = "272.94", gives me a null.

Also I have to extract the amount -336.9 from string strAmountString = "$272.94/mo for 24 months Regular Price -$336.9"

Upvotes: 3

Views: 1313

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347314

Your first issue, with trying to use 272.94, is related to the requirements of your regular expression, the fact that there is a requirement for the String to be lead by a $

You could make $ part of an optional group, for example ((\\$)?\\d+.\\d+), which will match both 272.94 and $272.94, but won't match -$336.9 directly, it will match $336.9 though.

So, working off your example, you could use ((-)?(\\$)?\\d+.\\d+) which will now match -$336.9 as well...

Personally, I might use ((-)?(\\$)?(-)?\\d+.\\d+), which will match -$336.9, $-336.9, -336.9 and 336.9

The next step would be try remove $ from the result, yes, you could try using another regular expression, but to be honest, String#replaceAll would be easier...

Note- My regular expression knowledge is pretty basic, so there might be simpler soltion

Updated with example

String value = "$272.94/mo for 24 months Regular Price -$336.9";
String regExp = "((-)?(\\$)?(-)?\\d+.\\d+)";

Pattern p = Pattern.compile(regExp);
Matcher matcher = p.matcher(value);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Which outputs...

$272.94
-$336.9

Upvotes: 2

David Koelle
David Koelle

Reputation: 20824

First, you need to make the dollar sign in your Pattern optional - or in other words, it needs to exist 0 or more times. Use the * qualifier.

Second, if you're sure that the dollar amount will always be at the beginning of the string, you can use the ^ boundary matcher, which indicates the beginning of the line.

Similarly, if you're sure that the final dollar amount will always be at the end of the line, you can use the $ boundary matcher.

See more details here: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Test your patterns here: http://www.regexplanet.com/advanced/java/index.html

Upvotes: 0

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28379

The following reg ex will get you your two groups (as group 1 and group 3)

(\\$\\d+\\.\\d+)(.*)?(\\-?\\$\\d+\\.\\d+)

Upvotes: 0

Related Questions