0

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)

8
  • Is this Python 2 or 3? What sample input can you give us that doesn't match? Commented Jul 22, 2014 at 10:45
  • @MartijnPieters Python 2.6 Commented Jul 22, 2014 at 10:46
  • Are your strings unicode objects or byte strings? Commented Jul 22, 2014 at 10:47
  • @MartijnPieters I have posted the string above. Sorry I dont understand what you are asking for Commented Jul 22, 2014 at 10:48
  • Note that [\w+^\w|d] is not a grouping but a character class. You are matching one character that is a member of the set \w, +, ^, | or d. Commented Jul 22, 2014 at 10:53

1 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

5 Comments

It fails in case of word separated with spaces Model Number: Virtual Box
@Pilot use [-\s\w]+ in that case.
@hjpotter92 Results 'Model Number: ST500DM002-1BD142 \n\tSerial Number'
@Pilot use Model Number:\s*([^\n]+)
sure. May i add that to my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.