Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

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 194 views
1 answer 165 views
1 answer 114 views
2 answers 101 views
1 answer 79 views
1 answer 143 views
1 answer 115 views
...