How to extract the last number from string in Java

3 Answers

0 votes
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyClass {
    public static void main(String args[]) {
        String s = "412hjdsf72q1p0on8mqjava9953";
 
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(s);
        
        int n = 0;
        while (m.find()) {
            n = Integer.parseInt(m.group());
        }
        
        System.out.println(n);
    }
}
 
 
 
 
/*
run:
 
9953
 
*/

 



answered Dec 16, 2020 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String str = "412hjdsf72q1p0on8mqjava9953"; 
 
        String[] arr = str.split("\\D+");
 
        int number = Integer.parseInt(arr[arr.length - 1]);
 
        System.out.print(number);
    }
}
 
  
  
  
/*
run:
       
9953
    
*/

 



answered Oct 5, 2023 by avibootz
0 votes
public class MyClass {
    public static int extractLastNumberFromString(String str) {
        String[] arr = str.split("\\D+");
 
        return Integer.parseInt(arr[arr.length - 1]);
    }
    public static void main(String args[]) {
        String str = "412hjdsf72q1p0on8mqjava9953"; 
 
        int number = extractLastNumberFromString(str);
 
        System.out.print(number);
    }
}
 
  
  
  
/*
run:
       
9953
    
*/

 



answered Oct 5, 2023 by avibootz

Related questions

2 answers 221 views
1 answer 180 views
1 answer 125 views
2 answers 117 views
1 answer 85 views
1 answer 146 views
1 answer 134 views
...