Deepak Ingole
Deepak Ingole

Reputation: 15732

Extract word from string Using python regex

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)

Upvotes: 0

Views: 15338

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

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.

Upvotes: 6

Related Questions