2014-02-21 58 views
0

我对于正则表达式和实践中的学习很陌生。我写了下面的正则表达式来查找字符串中的数字,但是,它什么都不返回。这是为什么?找到字符串中的数字REGEX

string = "hello world & bello stack 12456"; 

findObj = re.match(r'[0-9]+',string,re.I); 

if findObj: 
    print findObj.group(); 
else: 
    print "nothing matched" 

问候

+0

使用're.search'。 –

回答

3

re.match必须从字符串的开头相匹配。 改为使用re.search

+0

如何找到组的长度?每个子字符串是否由组(i)返回? –

+0

're.search'只能找到第一个匹配(如果有的话)。如果您想要所有匹配,请使用[re.findall](http://docs.python.org/2/library/re.html#re.findall)。 – unutbu

+0

非常感谢。如果你可以参考一个简单易学的Python文档/教程,就像Android文档一样,那会很棒。 –

3

re.match匹配字符串的开头。使用re.search

>>> my_string = "hello world & bello stack 12456" 
>>> find_obj = re.search(r'[0-9]+', my_string, re.I) 
>>> print find_obj.group() 
12456 

P.S分号是没有必要的。