0

I am very new to regex and learning by practice. I wrote the following regex for finding a number inside a string of characters, however, it returns nothing. Why is that?

string = "hello world & bello stack 12456";

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

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

Regards

Umer Farooq
  • 7,356
  • 7
  • 42
  • 67

2 Answers2

3

re.match must match from the beginning of the string. Use re.search instead.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • And how can I find the length of groups? Does each substring is returned by group(i)? – Umer Farooq Feb 21 '14 at 13:11
  • `re.search` only finds the first match (if any). If you want all matches, use [re.findall](http://docs.python.org/2/library/re.html#re.findall). – unutbu Feb 21 '14 at 13:26
  • thanks alot. If you can refer me to an easy to learn python documentation/tutorial just like Android documentation, that would be great. – Umer Farooq Feb 21 '14 at 13:49
  • I don't know what the Android docs are like, but for Python I would start by reading the [Python3 tutorial](http://docs.python.org/3/tutorial/) or [Python2 tutorial](http://docs.python.org/2.7/tutorial/), depending on the version of Python you are using. – unutbu Feb 21 '14 at 14:00
3

re.match matches from the start of the string. Use 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 semicolons are not necessary.

msvalkon
  • 11,887
  • 2
  • 42
  • 38