I'd like to use regex with Java.
What I want to do is find the first integer in a string.
Example:
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");
makeMatch.find();
String inputInt = makeMatch.group();
System.out.println(inputInt);
What am I doing wrong?
It looks like the other solutions failed to handle
+/-
and cases like2e3
, whichjava.lang.Integer.parseInt(String)
supports, so I'll take my go at the problem. I'm somewhat inexperienced at regex, so I may have made a few mistakes, used something that Java's regex parser doesn't support, or made it overly complicated, but the statements seemed to work in Kiki 0.5.6.All regular expressions are provided in both an unescaped format for reading, and an escaped format that you can use as a string literal in Java.
To get a byte, short, int, or long from a string:
...and for bonus points...
To get a double or float from a string:
Heres a handy one I made for C# with generics. It will match based on your regular expression and return the types you need:
then if you wanted to grab only the numbers and return them in an string[] array:
Hopefully this is useful to someone...
Use one of them:
or
You're asking for 0 or more digits. You need to ask for 1 or more:
In addition to what PiPeep said, if you are trying to match integers within an expression, so that
1 + 2 - 3
will only match1
,2
, and3
, rather than1
,+ 2
and- 3
, you actually need to use a lookbehind statement, and the part you want will actually be returned byMatcher.group(2)
rather than justMatcher.group()
.Also, for things like
someNumber - 3
, wheresomeNumber
is a variable name or something like that, you can useAlthough of course that wont work if you are parsing a string like
The net change to blahblah was +4
the java spec actually gives this monster of a regex for parsing doubles. however it is considered bad practice, just trying to parse with the intended type, and catching the error, tends to be slightly more readable.