Java floating-point number in String

let's say I have a line like this:

ExampleString> 1.67 -> ReSTOfString

my task is to extract only 1.67 from the line above.

I assume regex will be useful, but I can't figure out how to write a propper expression.

+2
source share
6 answers

If you want to extract all Int and Float from String , you can follow my solution:

 private ArrayList<String> parseIntsAndFloats(String raw) { ArrayList<String> listBuffer = new ArrayList<String>(); Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+"); Matcher m = p.matcher(raw); while (m.find()) { listBuffer.add(m.group()); } return listBuffer; } 

If you want to analyze negative values as well, can you add [-]? into the template as follows:

  Pattern p = Pattern.compile("[-]?[0-9]*\\.?[0-9]+"); 

And if you also want to set , as a separator , you can add ,? into the template as follows:

  Pattern p = Pattern.compile("[-]?[0-9]*\\.?,?[0-9]+"); 

.

To check the patterns, you can use this online tool: http://gskinner.com/RegExr/

Note. For this tool, remember unescape if you are trying to use my examples (you just need to remove one of \ )

+6
source

You can try matching numbers using regex

 \\d+\\.\\d+ 

It might look something like this:

 Pattern p = Pattern.compile("\\d+\\.\\d+"); Matcher m = p.matcher("eXamPLestring>1.67>>ReSTOfString"); while (m.find()) { Float.parseFloat(m.group()); } 
+2
source
  String s = "eXamPLestring>1.67>>ReSTOfString>>0.99>>ahgf>>.9>>>123>>>2323.12"; Pattern p = Pattern.compile("\\d*\\.\\d+"); Matcher m = p.matcher(s); while(m.find()){ System.out.println(">> "+ m.group()); } 

Gives only floats

 >> 1.67 >> 0.99 >> .9 >> 2323.12 
+1
source

Here's how to do it in one line,

 String f = input.replaceAll(".*?([\\d.]+).*", "$1"); 

If you really want a float , here is how you do it on one line:

 float f = Float.parseFloat(input.replaceAll(".*?([\\d.]+).*", "$1")), 
+1
source

You can use the regex \d*\.?,?\d* This will work for float, e.g. 1.0 and 1.0

0
source

Look at the link , they will also explain a few things you need to keep in mind when creating such a regular expression.

[-+]?[0-9]*\.?[0-9]+

code example:

 String[] strings = new String[3]; strings[0] = "eXamPLestring>1.67>>ReSTOfString"; strings[1] = "eXamPLestring>0.57>>ReSTOfString"; strings[2] = "eXamPLestring>2547.758>>ReSTOfString"; Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+"); for (String string : strings) { Matcher matcher = pattern.matcher(string); while(matcher.find()){ System.out.println("# float value: " + matcher.group()); } } 

exit:

 # float value: 1.67 # float value: 0.57 # float value: 2547.758 
0
source

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


All Articles