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 check and extract a number from a String in Java

1 Answer

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

public class MyClass {
    public static String extractNumberFromString(String s) {
        Pattern pt = Pattern.compile("\\d+");
        Matcher mt = pt.matcher(s);
        
        if (mt.find()) {
            return mt.group();
        } else {
            return "not found";
        }
    }
    public static void main(String args[]) {
        String s = "Java 21 is a high-level, class-based, object-oriented programming language";

        String number = extractNumberFromString(s);
        
        System.out.println(number);
    }
}
 
  
  
  
/*
run:
       
21
    
*/

 



answered Oct 5, 2023 by avibootz

Related questions

2 answers 101 views
3 answers 277 views
1 answer 143 views
1 answer 98 views
2 answers 115 views
...