0

I want get the word 'MASTER_INACTIVE' in the string:

'p_esco_link->state = MASTER_INACTIVE; /*M-t10*/'

by searching reg-expression 'p_esco_link->state =' to find the following word.

I have to replace date accessing to API functions. I try some reg-expression in python 3.6, but it does not work.

pattern = '(?<=\bp_esco_link->state =\W)\w+'

if __name__ == "__main__":

    syslogger.info(sys.argv)

    if version_info.major != 3:

        raise Exception('Olny work on Python 3.x')

    with open(cFile, encoding='utf-8') as file_obj:
        lineNum = 0
        for line in file_obj:
            print(len(line))
            re_obj = re.compile(pattern)
            result = re.search(pattern, line)
            lineNum += 1
            #print(result)
            if result:
                print(str(lineNum) + ' ' +str(result.span()) + ' ' + result.group())

excepted Python re module can find the position of 'MASTER_INACTIVE' and put it into result.group(). error message is that Python re module find nothing.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

0

Your pattern is working fine,

enter image description here

Just change the bellow line in your code,

pattern = r'(?<=\bp_esco_link->state =\W)\w+'  # add r prefix

Check this sample work, I added line as your string.

import re

pattern = r'(?<=\bp_esco_link->state =\W)\w+'
line = 'p_esco_link->state = MASTER_INACTIVE; /*M-t10*/'

re_obj = re.compile(pattern)
result = re.search(pattern, line)

print(result.span())  # (21, 36)
print(result.group())  # 'MASTER_INACTIVE'

Check below question to get more understand about 'r' prefix,

Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58
  • Your're welcome @PopeB.Lei and please make this answer as the accepted one. It will help for other developers to select the best answer surely. – Kushan Gunasekera Jul 05 '19 at 10:41