3

I got string that contains currency ($50, $4) or text "not arranged". I need to extract the number or in case of the text replace with 0.

So for example

$45 would give me 45
 £55 would give me 55
not arranged gives 0 or nothing
       44 would give 44

I was told that .(.*[0-9]) works. It does but only if assume that the first character is a currency symbol. If we omit the symbol or add extra leading space it won't work. Most importantly I don't understand the code .(.*[0-9]). Could someone please explain?

When I was trying to create the regexp by myself I thought that [0-9]* would work but it doesn't. I thought that [0-9] stands for a digit so then I want to catch all digits I would use [0-9]*. but it doesn't work.

How would I replace the text "not arranged" with 0. I need only regexp code not java code.

I am using http://www.regexplanet.com/advanced/java/index.html for testing.

Radek
  • 13,941
  • 49
  • 152
  • 237

1 Answers1

2

Something like this (assuming the string to be tested is called subjectString):

String theNumbers = null;
Pattern regex = Pattern.compile("\\d+");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
    theNumbers = regexMatcher.group();
} 
else subjectString = "0";
zx81
  • 39,708
  • 9
  • 81
  • 104