【问题标题】:python regex keep only words that start with alphabet and continues with [a-zA-Z0-9]python 正则表达式只保留以字母开头并以 [a-zA-Z0-9] 继续的单词
【发布时间】:2018-11-01 09:41:32
【问题描述】:

鉴于此文本“hey a2a 3beauty hou\se heyYou2”,我想只保留以字母开头并以 a-z、A-Z 或数字继续的单词。所以这将是我想要的输出:“hey a2a heyYou2”。

到目前为止,我的解决方案是通过 text.split() 函数:

text = "hey a2a 3beauty hou\se heyYou2"
text = text.split()
text = [w for w in text if re.search(r"^[a-zA-Z][a-zA-Z0-9]*$", w) is not None]
' '.join(text)

Out[55]: 'hey a2a heyYou2'

有没有一种快速、更有效的方法可以使用正则表达式实现这一点,而无需将文本拆分为单词列表?

【问题讨论】:

  • re.sub(r'\s*(?<!\S)(?![a-zA-Z][a-zA-Z0-9]*(?!\S))\S+', '', text), demo, code.
  • 感谢维克托。这会比我的解决方案更快,对吧?
  • 不知道,不一定要更快,请随意测试。
  • @pyd 你已经在这里了,在 SO :) 每天观看正则表达式标签,尝试解决问题。
  • 酷,我会发布。

标签: python regex


【解决方案1】:

您可以使用带有以下正则表达式的单个 re.sub 调用:

\s*(?<!\S)(?![a-zA-Z][a-zA-Z0-9]*(?!\S))\S+

regex demo

详情

  • \s* - 0+ 个空格
  • (?&lt;!\S) - 前导空白边界
  • (?![a-zA-Z][a-zA-Z0-9]*(?!\S)) - 如果在当前位置的右侧有
    • [a-zA-Z] - 一封信
    • [a-zA-Z0-9]* - 0 个或多个字母数字字符
    • (?!\S) - 尾随空白边界
  • \S+ - 一个或多个非空白字符

Python code demo:

import re
text = "hey a2a 3beauty hou\se heyYou2"
print(re.sub(r"\s*(?<!\S)(?![a-zA-Z][a-zA-Z0-9]*(?!\S))\S+", "", text))
# => hey a2a heyYou2

【讨论】:

  • @Wiktor,你赢了 re :-) 不错的一个 +1
猜你喜欢
  • 2015-01-07
  • 2021-11-09
  • 2010-12-11
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多