Java String Manipulation: Extracting an integer and float from a string based on a pattern

I have two possible contents of the string. Obviously, the amounts are always changing, and I would like to extract key information and

Case 0: pricesString = "" Case 1: pricesString = "$0.023" Case 2: pricesString = "10+: $1.46 100+: $0.16 500+: $0.04" 

In Case 0 I would not want to do anything.

In Case 1 I would like to execute:

 article.addPrice(1, 0.023); 

In Case 2 I would like to execute:

 article.addPrice(10, 1.46); article.addPrice(100, 0.16); article.addPrice(500, 0.04); 

How can I extract this information so that I can call article.addPrice with the contained float and integer values?

+2
source share
2 answers

This looks like a job for regex:

 String pricesString = "10+: $1.46 100+: $0.16 500+: $0.04"; Pattern p = Pattern.compile("(\\d+)\\+: \\$(\\d\\.\\d\\d)"); Matcher m = p.matcher(pricesString); while (m.find()) { Intger.parseInt(m.group(1)); Double.parseDouble(m.group(2)); } 

You can choose one of three cases with a simple breakdown .length() . The code above is for the latter case. The rest is eaiser

+5
source

Use the regular expression \d+\.?\d* as often as possible. An array of results can be checked to see if it contains 0, 1, or more values.

If there is 0, this is Case 0 .

If it is, this is Case 1 . You can edit it with qunantity 1.

If there are more, you can do something like

 for(int i = 0; i < result.length / 2; i++) { articles.addArticle(Integer.parseInt(result[i]), Double.parseDouble(result[i+1])); } 
0
source

Source: https://habr.com/ru/post/893112/


All Articles