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,813
  • 52
  • 161
  • 255

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
  • 41,100
  • 9
  • 89
  • 105
  • It works but could you make it generic so it is not dependent on the currency sign? Something like "get number from a string and the number could start at any position"? – Radek Jul 17 '14 at 03:14
  • try this regex `(\\d+)`, finally print the group 1 . – Avinash Raj Jul 17 '14 at 03:20