How to return positive and negative numbers when reading a file

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to return positive and negative numbers when reading a file



I am writing a code that reads a file line by line and return only the following lines, as an example:



int int0 = (-953);
int int1 = (-411);
int int2 = 5471;
int int3 = 823;



After that I would like to return only the numbers both positive and negative. To do that, I wrote the following:


String str = line.replaceAll("\D+","");
System.out.println(str);



The result of running this code is:



0953
1411
25471
3823



The output that I seek is:



-953
-411
5471
823



How can I do that?





does the number can be float ?
– YCF_L
1 hour ago





@Thomas Look at the variable naming 0, 1, 2, 3, then look at the start of each output number ;)
– Glains
58 mins ago




3 Answers
3



If you want to capture the last sequence of digits in a line (optionally preceded by a minus sign), you can do it with a capturing group, something like this:


Pattern p = Pattern.compile(".*?(-?\d+)\D*$");
String line = "int int0 = (-953);";
Matcher m = p.matcher(line);
if (m.matches()) {
System.out.println(m.group(1));
}



Result:


-953



How about this?



Due to your situation where each number will be after a = and what I want to do here is to remove everything else just as you once tried in this part (after =).


=


=


s = s.split("=")[1].replaceAll("[^-0-9]", "");



Local test your input with:


public static void main(String... args) {
String ss = {"int int0 = (-953);", "int int1 = (-411);", "int int2 = 5471;", "int int3 = 823;"};
for (String s : ss) {
s = s.split("=")[1].replaceAll("[^-0-9]", "");
System.out.println(s);
}
}



Output will be:


-953
-411
5471
823



Use this: ([-+]?)d+






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results