How do I convert data to whole string when I have data using Regex

 6 months ago
source link: https://www.codesd.com/item/how-do-i-convert-data-to-whole-string-when-i-have-data-using-regex.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How do I convert data to whole string when I have data using Regex


I am getting data as string and would like to add in Array. But Data I am getting is as String and looking to store as Integer.

Code :

             public static List<Integer> PriceData = new ArrayList<Integer>();
             public static String FinalPrice;

                       Pattern Pricepattern = Pattern.compile("Price\\s*:\\s*(\\S*)");
                       Matcher Pricematcher = Pricepattern.matcher(Content);
                       if(Pricematcher.find()) {  //we've found a match
                           FinalPrice = Pricematcher.group(1);



                      catch(NumberFormatException N)


                          System.out.println("Invalid Price Data");


Output :

FinalPrice : "$10.35"

PriceData : It always goes to exception. Here I want to store 10.35.

If I declare Finalprice as Integer then also have same problem.

You can fix your regex to catch price only and also you should parse to float or double. Integer has no floating point so it throws exception. Also - NumberFormatException is runtime exception so you don't need try/catch here. Here's example:

public static void main (String[] args){
        String finalPrice = null;
        String price = "Price : \"$10.35\"";
        String regex = "Price\\s:\\s\"\\$(\\d+.\\d+)\"";
        Pattern Pricepattern = Pattern.compile(regex);
        Matcher Pricematcher = Pricepattern.matcher(price);
        if(Pricematcher.find()) {  //we've found a match
            finalPrice = Pricematcher.group(1);
        float parsedPrice = Float.parseFloat(finalPrice);

About Joyk

Aggregate valuable and interesting links.
Joyk means Joy of geeK