简体   繁体   中英

How to Extract digits from string?

I need to extract digital values from the below string, basically the values after dollar sign :

"Current Revenue Page1 : SP-A-B2Btest
 Current revenue: +$109,852.65
 Previous revenue: +$54,730.12
 Change revenue: +$55,122.53
 % Change revenue: 100.71%"

I need to calculate the change revenue by subtracting previous from the current for verification purpose. Please guide me on this.

Try the below code.

public class RegexExamples {
public static void main(String[] args)
{
    String str="+$109,852.65";
    String numbers;
     numbers=str.replaceAll("[^0-9.]", "");
    System.out.println("Numbers are: " + numbers);
}}

You can use RegEx to find your values (where stringToSearch is your string):

import java.util.regex.Matcher;
import java.util.regex.Pattern;
Pattern p = Pattern.compile(" ([0-9,.]{2,}) ");   // the pattern to search for
Matcher m = p.matcher(stringToSearch);
if (m.find()) {
    System.out.println(m.group(0)); // whole matched expression
    System.out.println(m.group(1)); // first
    System.out.println(m.group(2)); // second 
    System.out.println(m.group(3)); // third 
    System.out.println(m.group(3)); // fourth
}

I used the pattern ([0-9,.]{2,}) which selects any number with . or , , that is 2 or more digits long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM