2017-06-06 80 views
0

我正在嘗試搜索與簡併或非常「模糊」的字符串匹配的確切模式。在python中搜索簡併字符串

pattern = 'VGSGSGSGSAS' can be 10-50 characters long 
string = "VGSGSGGSGSGSGSGSERGSAS" or "VGSGSGSGSGSGAGERSAS" #it's actually 400 character long string 
string[11] = S|A 
re.search(pattern, string) #does not work 

所以串[11]是S或A.在此示例中,我在尋找在2個定義的字符串的模式,但是,我不想做2個獨立的字符串,因爲有實際上在400個字符串中有多個(至少4個)位置,每個字符最多有3個不同的選項。所以我會在24個不同的字符串中進行製作和搜索。這只是一個序列。我的一些序列會變成64個不同的字符串。一旦找到搜索結果,我想知道它開始和結束的位置,以及它實際匹配哪個字符串[11]字符(S或A)。任何想法如何我可以做這種模式匹配?謝謝!

+0

所以要居中的模式,它在目標字符串的第11位找到N或K?即鑑於模式是KVTMQNL – sln

+0

你是什麼意思由'哪裏字符串[11]是N或K'? – sln

+0

我知道這些字符串因VGSE'KVTMQ [N | K] L'NDRLAS而不同,但匹配的_pattern_是'KVTMQ [N | K] L'。因此_pattern_不固定,它是可變的。真奇怪的部分是你繼續扔_target_字符串中的_11th_位置,就好像它有意義一樣。我看到在目標字符串中的第11個位置標記了這個變量模式「KVTMQ [N | K] L」的結束。這是唯一的關係,沒有別的。如果你瞭解它們,正則表達式非常強大。儘管沒有任何知識,但我明白了爲什麼很難解釋你想要做什麼。 – sln

回答

0

你不需要爲正則表達式,簡單str.find()就足以找到它:

pattern = "KVTMQNL" # substring to find 
your_strings = ["VGSEKVTMQNLNDRLAS", "VGSEKVTMQKLNDRLAS"] # just a list of strings 
for source in your_strings: # go through each string in our list 
    print("String: {}\nEleventh character: {}".format(source, source[11])) 
    if source[11] in ("N", "K"): # check if it has `N` or `K` on its 11th position 
     index = source.find(pattern) # search for the pattern 
     if index > -1: # if the pattern is found anywhere in the string... 
      print("Pattern start: {}\nPattern end: {}".format(index, index + len(pattern))) 
     else: 
      print("No match!") 
    print("---") 

這將打印出:

如果
String: VGSEKVTMQNLNDRLAS 
Eleventh character: N 
Pattern start: 4 
Pattern end: 11 
--- 
String: VGSEKVTMQKLNDRLAS 
Eleventh character: N 
No match! 
--- 

不知道這是你在尋找什麼因爲,你的問題有點混亂。

+0

@ user2789176 - 上面的列表是表示不同的字符串,因爲這就是你的問題所暗示的。你還會怎麼知道屬於哪一個屬於另一個字符串? – zwer

0

其實,如果我從你的問題理解是正確的,你可以使用re.search()與像本例中的字符串列表:

import re 

strings = ["VGSEKVTMQNLNDRLAS", "GSEKVTMQNLNDRLAS", "DRLASKVTMQKL", "GSEKVKVTMQPLDRLAS"] 
pattern = r'KVTMQ[N|K]L' 

for k in strings: 
    s = re.search(pattern, k) 
    print("Search in: {} ".format(k), end = ' ') 
    if s: 
     print("Found: {} in position: {}".format(s.group(), s.span())) 
    else: 
     print("Not found") 

輸出:

Search in: VGSEKVTMQNLNDRLAS Found: KVTMQNL in position: (4, 11) 
Search in: GSEKVTMQNLNDRLAS Found: KVTMQNL in position: (3, 10) 
Search in: DRLASKVTMQKL Found: KVTMQKL in position: (5, 12) 
Search in: GSEKVKVTMQPLDRLAS Not found