2017-10-29 79 views
0

我想編寫一個正則表達式,它匹配所有包含字母數字字符+下劃線的單詞,但不包含相鄰兩個下劃線的單詞。其實我要選擇的話下面的正則表達式匹配,但不包含 「__」正則表達式匹配沒有兩個下劃線的單詞

正則表達式:[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

回答

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

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

+1

@mohammad這樣的詞:您需要在問題描述中更加精確,然後! – Jan

+0

@mohammad:已更新,現在應該可以使用,請參閱演示。 – Jan