【问题标题】:regex match words without two underscores next to each other正则表达式匹配没有两个下划线的单词
【发布时间】:2018-04-10 09:17:06
【问题描述】:

我想编写一个匹配所有包含字母数字字符+下划线的单词的正则表达式,但不匹配两个下划线相邻的单词。实际上我想选择匹配正则表达式但不包含“__”的单词

正则表达式:[A-Za-z](\w){3,}[A-Za-z0-9]

匹配示例:123dfgkjdflg4_aaaad12354

不匹配示例:1246asd__

【问题讨论】:

  • 为什么要标记python和django?
  • 你“必须”在正则表达式中这样做吗?只需检查 '__' 不在字符串中
  • @MJafarMash 希望将其添加到此正则表达式“[A-Za-z](\w){3,}[A-Za-z0-9]”
  • @MJafarMash 表示我想用上面的正则表达式匹配单词,但其中没有“__”。
  • @mohammad 检查它们是否与您的正则表达式匹配,如果它们确实检查了字符串中不存在的双下划线

标签: regex


【解决方案1】:

你可以使用

\b[a-z0-9A-Z]*__\w*\b|(\b[A-Za-z0-9]\w*[A-Za-z0-9]\b)

并使用第一组,见a demo on regex101.com


Python 这可能是
import re

rx = re.compile(r'\b[a-z0-9A-Z]*__\w*\b|(\b[A-Za-z0-9]\w*[A-Za-z0-9]\b)')

words = ['a__a', '123dfgkjdflg4_', 'ad', '12354', '1246asd__', 'test__test', 'test']

nwords = [match.group(1) 
            for word in words 
            for match in [rx.search(word)]
            if match and match.group(1) is not None]

print(nwords)
# ['ad', '12354', 'test']

或者在一个字符串中:

import re

rx = re.compile(r'\b[a-z0-9A-Z]*__\w*\b|(\b[A-Za-z0-9]\w*[A-Za-z0-9]\b)')

string = "a__a 123dfgkjdflg4_ ad 12354 1246asd__ test__test test"

nwords = filter(None, rx.findall(string))
print(nwords)
# ['ad', '12354', 'test']


请注意,您可以在不使用正则表达式的情况下完成所有这些操作(可能更快且更轻松):
words = ['a__a', '123dfgkjdflg4_', 'ad', '12354', '1246asd__', 'test__test', 'test']

nwords = [word 
            for word in words
            if "__" not in word and not (word.startswith('_') or word.endswith('_'))]
print(nwords)
# ['ad', '12354', 'test']

【讨论】:

  • 我不想匹配像 _abc 或 abc_ 这样的词
  • @mohammad:那你的问题描述需要更准确!
  • @mohammad:已更新,现在应该可以使用了,请参阅演示。
  • @mohammad:此外,您的问题最后确实与_ 匹配。
  • @mohammad:不用担心。已更新答案并显示了非正则表达式方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
  • 2021-11-07
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 2011-10-15
相关资源
最近更新 更多