正则表达式获得字符串中的第一个数字:100 2011-10-20 14:28:55 [英] Regex to get first number in string: 100 2011-10-20 14:28:55
本文介绍了正则表达式获得字符串中的第一个数字:100 2011-10-20 14:28:55的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是正则表达式的新手,并且想知道如何才能获得字符串中的第一个数字,如100 2011-10-20 14:28:55。在这种情况下,我希望它返回100,但数字也可能更短或更长。
I'm new to regular expressions, and was wondering how I could get only the first number in a string like 100 2011-10-20 14:28:55. In this case, I'd want it to return 100, but the number could also be shorter or longer.
我在想[0-9] +之类的东西,但它分别需要每一个数字(100,2001,10,...)
I was thinking about something like [0-9]+, but it takes every single number separately (100,2001,10,...)
谢谢。
推荐答案
尝试这匹配字符串中的第一个数字(其中可以不在字符串的开头):
Try this to match for first number in string (which can be not at the beginning of the string):
String s = "2011-10-20 525 14:28:55 10";
Pattern p = Pattern.compile("(^|\\s)([0-9]+)($|\\s)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(2));
}
这篇关于正则表达式获得字符串中的第一个数字:100 2011-10-20 14:28:55的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文