2017-02-26 126 views
1

我試圖通過在Python中使用正則表達式來濾除CPU信息以下CPU模型和CPU頻率。正則表達式來過濾CPU信息(Python)

Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz 
Genuine Intel(R) CPU T2400 @ 1.83GHz 

到目前爲止,這是我想出來的,但仍然很難過濾出第二個。

(?(?=.*\sCPU\[email protected])([a-zA-Z]\d+-\d+[a-zA-Z]+)|\d+.\d+GHz) 

我在尋找我的輸出是這樣的:

i5-2520M 2.50GHz 
Genuine T2400 1.83GHz 

謝謝大家先進

+0

下面是[一個簡單的例子](https://regex101.com/r/oKJOL3/1),它涵蓋了您提供的兩種情況......雖然我不確定它是否可以用於其他輸入字符串。 –

回答

0

這個答案與我發佈的第一個不同。在這裏,我試圖完全匹配在問題上匹配的內容。

這是新的活鏈接爲這樣的回答:https://regex101.com/r/sr3zjR/3

(?x) # Free spacing mode, to allow comment and better view 

# Matching the first line `i5-2520M`    (capture group 1) 
([^ ]+\s*)(?=CPU\s*@) 

# Matching the first line `@ 2.50GHz`    (capture group 2) 
|(?<=CPU)(\s*@\s*\d+.\d+GHz) 

# Matching the `first word` on the second line.  (capture group 3) 
# The `\s*$` is used to not match empty lines. 
|(^[^ ]+)(?!(?:.*CPU\s*@)|\s*$) 

# Matching the second line `CPU T2400`    (capture group 4) 
|(?<=CPU)(\s*[^ ]+\s*)([email protected]) 

# Matching the second line `1.83GHz`    (capture group 5) 
|\s*(?<[email protected])(\s*\d+.\d+GHz) 

這裏作爲對方的回答,每個捕獲組保持所需的元素之一,因此,你可以操縱的每一個他們通過他們的捕獲組索引來引用他們。


在組2,有我在哪裏匹配@允許其無限期和單詞之間的空格前,由於該positive look-behind (?<=)不允許使用*運營商的伎倆。你可以改變第二組表達這種波紋管,如果是不感興趣的匹配@

enter image description here

# Matching the first line `2.50GHz`     (capture group 2) 
|(?<=CPU\[email protected])(\s*\d+.\d+GHz) 

這是新的活鏈接爲這種變化:https://regex101.com/r/sr3zjR/5

上在這個答案上的其他地方,我們在自由間隔模式。此外,我們需要通過\來逃脫white-space,或者只是使用\s

+0

感謝您的明確解釋。 –

1

在此鏈接,您可以播放/個性化它:https://regex101.com/r/sr3zjR/1

enter image description here

(?x) # Free spacing mode, to allow comment and better view 

# Matching the first line `i5-2520M` 
([^ ]+\s*)(?=CPU\s*@) 

# Matching the first line `2.50GHz` 
|(?<=CPU)(\s*@\s*\d+.\d+GHz) 

# Matching the second line `CPU T2400` 
|(CPU\s*[^ ]+\s*)([email protected]) 

# Matching the second line `1.83GHz` 
|\s*(?<[email protected])(\s*\d+.\d+GHz) 

由於正則表達式的性質,我們不能跳過/跳轉正則表達式序列,這就是爲什麼我們需要使用|運算符爲每個捕獲組創建幾個匹配。因此,你可以看到這個其他問題進行更深入的瞭解:Regular expression to skip character in capture group


這些都是黃金的地方路過:

  1. http://www.rexegg.com/regex-quickstart.html
  2. https://regexone.com/
  3. http://www.regular-expressions.info/quickstart.html
  4. Reference - What does this regex mean?