mscccc mscccc - 1 year ago 68
Java Question

Regex to find an integer within a string

I'd like to use regex with Java.

What I want to do is find the first integer in a string.


String = "the 14 dogs ate 12 bones"

Would return 14.

String = "djakld;asjl14ajdka;sdj"

Would also return 14.

This is what I have so far.

Pattern intsOnly = Pattern.compile("\\d*");
Matcher makeMatch = intsOnly.matcher("dadsad14 dssaf jfdkasl;fj");
String inputInt =;

What am I doing wrong?

Answer Source

You're asking for 0 or more digits. You need to ask for 1 or more:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download