0

Possible Duplicate:
Java: how to check that a string is parsable to a double?

What is the best way to check a string for numeric characters in Java?

    try {
        NumberFormat defForm = NumberFormat.getInstance();            
        Number n = defForm.parse(s);      
        double d = n.doubleValue();
    } 
    catch (Exception ex) {
        // Do something here...    
    } 

Or is there a better way using REGEX?

I don't want to strip the numbers.

Community
  • 1
  • 1
Mr Morgan
  • 2,215
  • 15
  • 48
  • 78

4 Answers4

2
String test = "12cats";
//String test = "catscats";
//String test = "c4ts";
//String test = "12345";
if (test.matches(".*[0-9].*") {
    System.out.println("Contains numbers");
} else {
    System.out.println("Does not contain numbers");
} //End if
Jason Sturges
  • 15,855
  • 14
  • 59
  • 80
swapy
  • 1,616
  • 1
  • 15
  • 31
1

using regex u can do it this way -

String s="aa56aa";
Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(s);

System.out.println(matcher.find());
Kshitij
  • 8,474
  • 2
  • 26
  • 34
0

A good solution would be to use a regex (link <- here you have everything you need to work wih regexes).

overbet13
  • 1,654
  • 1
  • 20
  • 36
0
/**
 * Return true if your string contains a number,
 * false otherwise.
 */
str.matches("\\d+");

e.g.:

"csvw10vsdvsv".matches("\\d+"); // true
"aaa".matches("\\d+"); // false
user278064
  • 9,982
  • 1
  • 33
  • 46