please tell me what I'm doing wrong, I need to get the value
here is the part of the code that is responsible for:
my code:
dict_miner['model'] = re.search(r'SN: (\w )', date.get('Name'))
result:
'model': <re.Match object; span=(14, 21), match='sn: abc123456'>
but I need the value of match to be written to the variable:
my code:
dict_miner['model'] = re.search(r'SN: (\w ).group(1)', date.get('Name'))
result:
'model': None,
as a result , why doesn 't it work .group(1)?
result = 'model': abc123456
or should I throw off the entire code ?
CodePudding user response:
The group(1)
invocation is Python code, not part of the regexp.
dict_miner['model'] = re.search(r'SN: (\w )', date.get('Name')).group(1)
Note that this will happily crash if the data does not match; then re.search would return None
, and you can't call group on None
. You will need to do this in two steps, like so, to take care of that.
name_match = re.search(r'SN: (\w )', date.get('Name'))
dict_miner['model'] = (name_match.group(1) if name_match else None)