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,085
  • 14
  • 46
  • 78

5 Answers5

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,787
  • 14
  • 60
  • 77
swapy
  • 1,586
  • 1
  • 14
  • 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,218
  • 2
  • 23
  • 34
0

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

overbet13
  • 1,666
  • 1
  • 19
  • 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,778
  • 1
  • 32
  • 46
0
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher("125455");
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100