首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过滤掉CPU信息的Regex (Python)

过滤掉CPU信息的Regex (Python)
EN

Stack Overflow用户
提问于 2017-02-26 03:08:13
回答 2查看 653关注 0票数 1

我试图使用Python中的Regex过滤出CPU模型和cpu频率下面的cpu信息。

代码语言:javascript
复制
Intel(R) Core(TM) i5-2520M CPU @ 2.50GHz
Genuine Intel(R) CPU T2400 @ 1.83GHz

到目前为止,这是我提出的,但仍然有困难的时间过滤掉第二个。

代码语言:javascript
复制
(?(?=.*\sCPU\s@)([a-zA-Z]\d+-\d+[a-zA-Z]+)|\d+.\d+GHz)

我在我的输出中寻找这样的东西:

代码语言:javascript
复制
i5-2520M  2.50GHz
Genuine T2400  1.83GHz 

谢谢你们的进阶

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-26 04:53:04

这个答案和我发布的第一个不一样。在这里,我试图准确地匹配在问题上匹配的内容。

这是这个答案的新的实时链接:https://regex101.com/r/sr3zjR/3

代码语言:javascript
复制
(?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 (?<=)不允许使用*运算符。如果与@不匹配,则可以将第二个组表达式更改为下面所示

代码语言:javascript
复制
# Matching the first line `2.50GHz`                 (capture group 2)
|(?<=CPU\s@)(\s*\d+.\d+GHz)

这是此更改的新活动链接:https://regex101.com/r/sr3zjR/5

和这个答案上的其他地方一样,我们是在自由间距模式下。此外,我们还需要用\来转义\,或者只使用\s

票数 0
EN

Stack Overflow用户

发布于 2017-02-26 04:03:38

在这个链接上,您可以播放/个性化它:https://regex101.com/r/sr3zjR/1

代码语言:javascript
复制
(?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

这些都是可以经过的黄金地方:

  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?
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42464298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档