我试图使用Python中的Regex过滤出CPU模型和cpu频率下面的cpu信息。
Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz
Genuine Intel(R) CPU T2400 @ 1.83GHz到目前为止,这是我提出的,但仍然有困难的时间过滤掉第二个。
(?(?=.*\sCPU\s@)([a-zA-Z]\d+-\d+[a-zA-Z]+)|\d+.\d+GHz)我在我的输出中寻找这样的东西:
i5-2520M 2.50GHz
Genuine T2400 1.83GHz 谢谢你们的进阶
发布于 2017-02-26 04:53:04
这个答案和我发布的第一个不一样。在这里,我试图准确地匹配在问题上匹配的内容。
这是这个答案的新的实时链接: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*)(?=@)
# Matching the second line `1.83GHz` (capture group 5)
|\s*(?<=@)(\s*\d+.\d+GHz)在这里,与另一个答案一样,每个捕获组都持有所需的元素之一,因此您可以通过引用每个元素的捕获组索引来单独操作它们。
在第2组中,有一个技巧,就是我要匹配@,允许它和它前面的单词之间无限期的空格,因为positive look-behind (?<=)不允许使用*运算符。如果与@不匹配,则可以将第二个组表达式更改为下面所示

# Matching the first line `2.50GHz` (capture group 2)
|(?<=CPU\s@)(\s*\d+.\d+GHz)这是此更改的新活动链接:https://regex101.com/r/sr3zjR/5
和这个答案上的其他地方一样,我们是在自由间距模式下。此外,我们还需要用\来转义\,或者只使用\s。
发布于 2017-02-26 04:03:38
在这个链接上,您可以播放/个性化它:https://regex101.com/r/sr3zjR/1

(?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*)(?=@)
# Matching the second line `1.83GHz`
|\s*(?<=@)(\s*\d+.\d+GHz)由于regex特性,我们不能跳过/跳regex序列,这就是为什么我们需要使用|操作符为每个捕获组创建几个匹配。因此,您可以看到另一个更有洞察力的问题:Regular expression to skip character in capture group
这些都是可以经过的黄金地方:
https://stackoverflow.com/questions/42464298
复制相似问题