Extract word from string Using python regex

戏子无情 提交于 2021-02-08 09:56:55

问题


I want to extract a Model Number from string ,

/dev/sda:

ATA device, with non-removable media
    Model Number:       ST500DM002-1BD142                       
    Serial Number:      W2AQHKME
    Firmware Revision:  KC45    
    Transport:          Serial, SATA Rev 3.0

Regex I wrote,

re.search("Model Number:(\s+[\w+^\w|d]\n\t*)", str)

But issue is, its not matching any special characters (non ascii) in string str

Python 2.6

Note: String can be combination any characters/digits (including special)


回答1:


Your regex would be,

Model Number:\s*([\w-]+)

Python code would be,

>>> import re
>>> s = """
... 
... /dev/sda:
... 
... ATA device, with non-removable media
...     Model Number:       ST500DM002-1BD142                       
...     Serial Number:      W2AQHKME
...     Firmware Revision:  KC45    
...     Transport:          Serial, SATA Rev 3.0"""
>>> m = re.search(r'Model Number:\s*([^\n]+)', s)
>>> m.group(1)
'ST500DM002-1BD142'

Explanation:

  • Model Number:\s* Matches the string Model Number: followed by zero or more spaces.
  • ([^\n]+) Captures any character but not of a newline character one or more times.


来源:https://stackoverflow.com/questions/24885262/extract-word-from-string-using-python-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!