【问题标题】:How can I exclude strings containing numbers with Regex?如何使用正则表达式排除包含数字的字符串?
【发布时间】:2021-05-06 20:57:20
【问题描述】:

这是我当前的代码:

import re
start_line = 163
with open('file.txt') as f:
  lines = f.readlines()[start_line:]
  lines = '\n'.join(lines)
words = re.findall(r'\$\w+', lines)

这会创建一个这样的列表:

[‘$ALPP’, ‘$ABML’, ‘$700’, ‘$15M’]

如何使用正则表达式排除任何包含数字的字符串?

【问题讨论】:

  • 是否需要使用正则表达式?
  • @BuddyBob 是的,因为我正在尝试学习正则表达式

标签: python regex


【解决方案1】:

\w 等价于 [a-zA-Z0-9_],因此它包含数字。改用 \D (任何非数字)之类的东西。

提示:使用https://regex101.com/ 之类的网站来测试您的正则表达式、阅读说明并随时获得视觉反馈。

【讨论】:

  • 正如@WiktorStribiżew 所说,\w 默认不等同于[A-Za-z0-9_]read the docs了解更多信息
  • 在没有太多描述的情况下发布链接作为答案是违反规则的
  • 据我所知,这条规则只适用于答案,不适用于 cmets。顺便说一句,我通过指出这不是默认行为来提供上下文,可以在文档中阅读更多内容。
【解决方案2】:

试试这个:

import re
start_line = 163
with open('file.txt') as f:
    lines = f.readlines()[start_line:]
    lines = '\n'.join(lines)
    words = re.findall(r'\$[a-zA-Z_]+', lines)

请注意,这也将排除带有非字母标点符号的单词,例如 it'sman-eatingstart_line,以及任何可能带有标点符号的单词,例如 word.在句末。如果这可能对您的数据很重要,只需在 [...] 中添加您想要包含的任何字符。

编辑: 地址 cmets。

【解决方案3】:

使用 ascii 字符串时,\w 等价于 [a-zA-Z0-9_]

所以你可以改用[a-zA-Z_]

【讨论】:

  • 在 Python 中,\w 默认不等同于[A-Za-z0-9_]
  • @WiktorStribiżew 你是对的,修复它
【解决方案4】:

使用

re.findall(r'\B\$[A-Za-z_]+\b', lines)

proof

解释

--------------------------------------------------------------------------------
  \B                       the boundary between two word chars (\w)
                           or two non-word chars (\W)
--------------------------------------------------------------------------------
  \$                       '$'
--------------------------------------------------------------------------------
  [A-Za-z_]+               any character of: 'A' to 'Z', 'a' to 'z',
                           '_' (1 or more times (matching the most
                           amount possible))
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2018-09-10
    • 2014-03-29
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多