Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract a number from a string using java reg exp? [duplicate]

Tags:

java

regex

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.

like image 823
Radek Avatar asked Dec 19 '25 01:12

Radek


1 Answers

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";
like image 119
zx81 Avatar answered Dec 20 '25 14:12

zx81