正则表达式在字符串中查找整数 [英] Regex to find an integer within a string

查看:356
本文介绍了正则表达式在字符串中查找整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中使用正则表达式。

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"

将返回14.

String = "djakld;asjl14ajdka;sdj"

也将返回14

这是我到目前为止。

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

我做错了什么?

推荐答案

您要求的是0位或更多位数。您需要索要1个或更多:

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

"\\d+"

这篇关于正则表达式在字符串中查找整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆