我想在Java中使用正则表达式。
我想要做的是找到字符串中的第一个整数。
示例:
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);
我做错了什么?
发布于 2008-12-16 18:08:24
您要求的位数为0或更多。您需要要求1个或更多:
"\\d+"
发布于 2009-10-23 04:08:15
这是我用泛型为C#做的一个方便的例子。它将根据您的正则表达式进行匹配,并返回您需要的类型:
public T[] GetMatches<T>(string Input, string MatchPattern) where T : IConvertible
{
List<T> MatchedValues = new List<T>();
Regex MatchInt = new Regex(MatchPattern);
MatchCollection Matches = MatchInt.Matches(Input);
foreach (Match m in Matches)
MatchedValues.Add((T)Convert.ChangeType(m.Value, typeof(T)));
return MatchedValues.ToArray<T>();
}
然后,如果您只想获取数字并在string[]数组中返回它们:
string Test = "22$data44abc";
string[] Matches = this.GetMatches<string>(Test, "\\d+");
希望这对某些人有用...
发布于 2012-12-21 03:11:17
除了PiPeep所说的,如果您试图匹配表达式中的整数,以便1 + 2 - 3
只匹配1
、2
和3
,而不是1
、+ 2
和- 3
,那么您实际上需要使用lookbehind语句,并且您想要的部分实际上将由Matcher.group(2)
返回,而不仅仅是Matcher.group()
。
unescaped: ([0-9])?((?(1)(?:[\+-]?\d+)|)(?:[eE][\+-]?\d+)?)
escaped: ([0-9])?((?(1)(?:[\\+-]?\\d+)|)(?:[eE][\\+-]?\\d+)?)
此外,对于像someNumber - 3
这样的东西,您可以使用
unescaped: (\w)?((?(1)(?:[\+-]?\d+)|)(?:[eE][\+-]?\d+)?)
escaped: (\\w)?((?(1)(?:[\\+-]?\\d+)|)(?:[eE][\\+-]?\\d+)?)
当然,如果您正在解析像The net change to blahblah was +4
这样的字符串,那么这是不起作用的
https://stackoverflow.com/questions/372148
复制相似问题