re.search - Pattern matching review
Ganesh Pal
ganesh1pal at gmail.com
Mon May 30 05:03:43 EDT 2016
On Sun, May 29, 2016 at 10:32 PM, Matt Wheeler <m at funkyhat.org> wrote:
>
>
> This doesn't seem to exactly match your code below, i.e. your code is
> attempting to construct a tuple from groups 1 through 4. To meet this
> specification I could just `return re.search('(?<=\(block
> )[^(]*(?=\))', stdout).group()`
>
> Thanks Matt for the reply and lovely analysis . I was trying to
complicate the simple task :(
Here is how the code looks now , the whole idea was just to match the
pattern and return it
def get_block(block):
cmd = "get_block_info -l"
stdout, stderr, exitcode = subprocess_run(cmd)
#Grab the block from the stdout
block = re.search('(?<=\(block )[^(]*(?=\))', stdout).group()
# check the pattern
matched = re.search(r'(\d+),(\d+),(\d+):(\d+)', block)
if matched:
logging.info('block found")
return block
else:
logging.info('block not found")
I had one final question. I was thinking if we included a try -expect
block to catch the failures of re.search as shown below.
what kind of specific exception can we add ( just the AttributeError
Exception or any thing else )
Example :
try:
block = re.search('(?<=\(block )[^(]*(?=\))', stdout).group()
matched = re.search(r'(\d+),(\d+),(\d+):(\d+)', block)
except AttributeError
logging.error(' Error: while determining the block ")
Regards,
Ganesh
More information about the Python-list
mailing list