0

My code is (in Python 2.7 using Anaconda),

import re
regex = r"([A-z]+) (\d+)"
str = "HELLO 3 hello this is REGEX example"
matchObject = re.search(regex, str)
print matchObject
if matchObject is not None:
    print matchObject.start()
    print matchObject.end()
    print matchObject.group(0)
    print matchObject.group(1)
    print matchObject.group(2)

When Regex search for pattern it return an output in this format:

line 1: <_sre.SRE_Match object at 0x10a2568b0>
line 2: 0
line 3: 7
line 4: HELLO 3
line 5: HELLO
line 6: 3

I have added line number in output for better understanding, line 1 of output is very confusing, and line 3 (output=7) is also confusing. Can you explain line 1 and line 3 of output?

Naeem Ul Wahhab
  • 2,465
  • 4
  • 32
  • 59

1 Answers1

2

Those print numbers correspond to the print statements

print matchObject #line 1, python has to interpret your regex match object as a string and gives it's type and address
if matchObject is not None:
    print matchObject.start() #line 2, the full match is "HELLO 3", this is zero chars away from the start of the input
    print matchObject.end() #line 3, the full match is "HELLO 3", which ends after 7 characters
    print matchObject.group(0) #line 4, the full match (regex group 0) is "HELLO 3"
    print matchObject.group(1) #line 5, you captured HELLO with the first parens
    print matchObject.group(2) #line 6, you captured 3 with the second

nothing here seems incorrect to me

Austin_Anderson
  • 900
  • 6
  • 16
  • Thanks @Austin, for clearing line 3, but line 1 of output is still confusing – Gaurav Rathore Aug 14 '17 at 19:35
  • 1
    `re.search()` returns an __object__ that has the `start` method, the `end` method and the `group` method as well as the data that those methods use. When you print an object, that object must be converted to a string, using the `__repr__` method. If it's not defined specifically for a type, as is the case for the regex match object, it makes a string with the object type, and where in memory the instance of that object is – Austin_Anderson Aug 14 '17 at 19:45