這個答案與我發佈的第一個不同。在這裏,我試圖完全匹配在問題上匹配的內容。
這是新的活鏈接爲這樣的回答: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 (?<=)
不允許使用*
運營商的伎倆。你可以改變第二組表達這種波紋管,如果是不感興趣的匹配@
:
# 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
。
下面是[一個簡單的例子](https://regex101.com/r/oKJOL3/1),它涵蓋了您提供的兩種情況......雖然我不確定它是否可以用於其他輸入字符串。 –