[Solved] How to extract an alphanumeric string from a sentence if a starting point and end point is given [closed]


Using regex

Code

import re

def extract(text):
    '''
       extract substring
    '''
    pattern = r'^G.*[794]'  # pattern ends in 7, 9, 4
    
    # Find pattern in text
    m = re.match(pattern, text)       # find pattern in string
    if m:
        # Found pattern substring
        # Remove space, \, (, - by replacing with empty string
        m = re.sub(r'[ \(/-]', '', m.group())
    return m

Usage

s = "GAP-88 (R 07/17) (STOCK REORDER NUMBER)"
print(extract(s))   # Output: GAP88R0717

Explanation

r'^G.*[794]'          - regex match pattern
'^G                   - match strings that begins with G
.*[794]               - greedily match all characters 
                        until last 7, 9, or 4 
                        in string

Follow up Question

To detect text word after (STOCK REORDER NUMBER)

Code

def postfix(text):
    '''
        Extract text after (STOCK REORDER NUMBER)
    '''
    pattern = r'\(STOCK REORDER NUMBER\)\s(\w+)'
    m = re.search(pattern, text)
    if m:
        return m.group(1)
    else:
        return ''

Usage

s = "GAP-88 (R 07/17) (STOCK REORDER NUMBER) abc123"
print(postfix(s)) # Output: abc123

print(extract(s) + ' ' + postfix(s))
# Output: GAP88R0717 abc123

4

solved How to extract an alphanumeric string from a sentence if a starting point and end point is given [closed]