正则表达式匹配没有两个下划线的单词

问题描述:

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

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

匹配例如:123dfgkjdflg4_aaaad12354

不匹配例如:1246asd__

+0

为什么python和djang o标记? – gommb

+3

你是否需要用正则表达式来做呢?只是检查'__'不在字符串中 –

+0

@MJafarMash想要将它添加到此正则表达式中“[A-Za-z](\ w){3,} [A-Za-z0-9]” – mohammad

你可以使用

\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'] 
+0

我不想匹配像\ _abc或abc \ _ – mohammad

+1

@mohammad这样的词:您需要在问题描述中更加精确,然后! – Jan

+0

@mohammad:已更新,现在应该可以使用,请参阅演示。 – Jan