loki
loki

Reputation: 972

Strip special characters in front of the first alphanumeric character

I have a regex that picks up address from data. The regex looks for 'Address | address | etc.' and picks up the characters following that until occurrence of 4 integers together. This includes special characters, which need to be stripped.

I run a loop to exclude all the special characters as seen in the code below. I need the code to drop only the special characters that are present in front of the first alphanumeric character.

Input (from OCR on an image):
Service address —_Unit8-10 LEWIS St, BERRI,SA 5343

        possible_addresses = list(re.findall('Address(.* \d{4}|)|address(.*\d{4})|address(.*)', data)) 
        address            = str(possible_addresses[0])

        for k in address.split("\n"): 
            if k != ['(A-Za-Z0-9)']:
                address_2 = re.sub(r"[^a-zA-Z0-9]+", ' ', k)

Got now:
address : —_Unit 8 - 10 LEWIS ST, BERRI SA 5343
address_2 : Unit 8 10 LEWIS ST BERRI SA 5343

Upvotes: 0

Views: 73

Answers (2)

Smart Manoj
Smart Manoj

Reputation: 5834

[\W_]* captures the special chars.

import re
data='Service address —_Unit8-10 LEWIS St, BERRI,SA 5343'
possible_addresses = re.search('address[\W_]*(.*?\d{4})', data,re.I)
address = possible_addresses[1]
print('Address : ' address)

Address : Unit8-10 LEWIS St, BERRI,SA 5343

Upvotes: 1

Emma
Emma

Reputation: 27723

I'm guessing that the expression we wish to design here should be swiping everything from address to a four-digit zip, excluding some defined chars such as _. Let's then start with a simple expression with an i flag, such as:

(address:)[^_]*|[^_]*\d{4}

Demo

Any char that we do not want to have would go in here [^_]. For instance, if we are excluding !, our expression would become:

(address:)[^_!]*|[^_!]*\d{4}

Test

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

import re

regex = r"(address:)[^_]*|[^_]*\d{4}"

test_str = ("Address: Unit 8 - 10 LEWIS ST, BERRI SA 5343 \n"
    "Address: Got now: __Unit 8 - 10 LEWIS ST, BERRI SA 5343\n"
    "aDDress: Unit 8 10 LEWIS ST BERRI SA 5343\n"
    "address: any special chars here !@#$%^&*( 5343\n"
    "address: any special chars here !@#$%^&*( 5343")

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

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.

Upvotes: 0

Related Questions