正则表达式匹配没有两个下划线的单词
问题描述:
我想编写一个正则表达式,它匹配所有包含字母数字字符+下划线的单词,但不包含相邻两个下划线的单词。其实我要选择的话下面的正则表达式匹配,但不包含 “__”正则表达式匹配没有两个下划线的单词
正则表达式:[A-Za-z](\w){3,}[A-Za-z0-9]
匹配例如:123dfgkjdflg4_aaa
,ad
,12354
不匹配例如:1246asd__
答
在
需要注意的是,你可以做到这一切没有一个正则表达式(快可能和更低的头痛) :
你可以使用
\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']
为什么python和djang o标记? – gommb
你是否需要用正则表达式来做呢?只是检查'__'不在字符串中 –
@MJafarMash想要将它添加到此正则表达式中“[A-Za-z](\ w){3,} [A-Za-z0-9]” – mohammad