regex to match words that doesn't contain symbols

Viewed 140

I am trying to capture words that come after a certain pattern \d+", I want to capture all the words after the pattern until "&" or a number is found in the word.

this is what I have so far

import re
tests = ['the size will be 12" QTR', 'size is 7" gnh H&M','size is 12" GNH.M gm H&M', 'sizes are 12" QTR gm Best&SAP for all ages', 'size is 14" qtr 14GM']
for i in tests:
    temp = re.search('\d+"\s+([A-Za-z.\s]+)', i).groups()[0]
    print(temp)

the expected output is

QTR
gnh
GNH.M gm
QTR gm
qtr
3 Answers

first replace all characters of word that contain & with & then run your code like this:

import re
tests = ['the size will be 12" QTR', 'size is 7" gnh H&M','size is 12" GNH.M gm H&M', 'sizes are 12" QTR gm Best&SAP for all ages', 'size is 14" qtr 14GM']
for j,i in enumerate(tests):
    for word in i.split():
        if "&" in word:
            i = i.replace(word, '&'*len(word))
    tests[j] = i
    temp = re.search('\d+"\s+([A-Za-z.\s]+)', i).groups()[0]
    print(temp)

print(tests)

output:

QTR
gnh 
GNH.M gm 
QTR gm 
qtr 

after running this code your tests list become like this:

['the size will be 12" QTR',
 'size is 7" gnh &&&',
 'size is 12" GNH.M gm &&&',
 'sizes are 12" QTR gm &&&&&&&& for all ages',
 'size is 14" qtr 14GM']

You could use a non-capturing group (?:\d+\w+|\w+&|$) to match all words until the & or a number is found in the word.

import re
tests = ['the size will be 12" QTR', 'size is 7" gnh H&M',
            'size is 12" GNH.M gm H&M', 'sizes are 12" QTR gm Best&SAP for all ages',
            'size is 14" qtr 14GM']
for i in tests:
    temp = re.search('\d+"\s+(.*?)\s?(?:\d+\w+|\w+&|$)', i).groups()[0]
    print(temp)
QTR
gnh
GNH.M gm
QTR gm
qtr

Regex101 sample

You can use

\d+"\s*([^\d&]+)(?!\S)

See the regex demo. Details:

  • \d+ - one or more digits
  • " - a double quote
  • \s* - zero or more whitespaces
  • ([^\d&]+) - Group 1: any one or more chars other than a digit and &
  • (?!\S) - the next char must be end of string or a whitespace.

See the Python demo:

import re
tests = ['the size will be 12" QTR', 'size is 7" gnh H&M','size is 12" GNH.M gm H&M', 'sizes are 12" QTR gm Best&SAP for all ages', 'size is 14" qtr 14GM']
for test in tests:
    match = re.search(r'\d+"\s*([^\d&]+)(?!\S)', test)
    if match:
        print(match.group(1))

Output:

QTR
gnh
GNH.M gm
QTR gm
qtr
Related