-1

I need to write a strip function using regex.

This is my current code:

import re

def makestringstripfun(text):
    stripStringRegex = re.compile(r'(^.*?)(\w+)( +\w+)*(\s|.*?)$')
    match = stripStringRegex.search(text)
    print(match)

print('Enter the string:')
text = input()
makestringstripfun(text)

I want to output the entire string, whatever I enter. Right now, if I enter the following text:

smith john go home your shift getting over in the 30 minute later then why you here

the output of my code is:

<_sre.SRE_Match object; span=(0, 84), match='smith john go home your shift getting over in t>
wovano
  • 4,543
  • 5
  • 22
  • 49
Patel
  • 1
  • 1

2 Answers2

0

The search() method returns a match object, not a string.

See the documentation of match objects how to handle these. In short, you can use match.group(0) to get the first match group.

Tip: on regex101.com you can easily test your regular expressions.

wovano
  • 4,543
  • 5
  • 22
  • 49
0

I'm not really sure, what we like to match here.

If you wish to just output the entire string, maybe we might want to modify our expression and add a capturing group, something similar to:

^((.*?)(\w+)( +\w+)*(\s|.*?))$

Demo

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"^((.*?)(\w+)( +\w+)*(\s|.*?))$"

test_str = "smith john go home your shift getting over in the 30 minute later then why you here"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69