正则表达式获取字符串中其他字符的第一个数字 [英] Regex to get first number in string with other characters
本文介绍了正则表达式获取字符串中其他字符的第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是正则表达式的新手,我想知道如何只获取字符串中的第一个数字,例如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));
}
这篇关于正则表达式获取字符串中其他字符的第一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文