2017-01-27 37 views
0

我有一個實際上包含很多其他子字符串的巨大字符串。當我運行我的代碼時,它無法正確掃描字符串並返回false值。Python來掃描包含各種其他字符串的字符串

目標:我試圖在字符串中搜索特定值,並希望將其存儲到變量中。

Code`import re 
mystring = "This 'is' the 'test' I am doing" 
searchObj = re.search(r'(.*) test (.*?) .*', mystring, re.M|re.I) 

if searchObj: 
    print "searchObj.group() : ", searchObj.group() 
    print "searchObj.group(1) : ", searchObj.group(1) 
    print "searchObj.group(2) : ", searchObj.group(2) 
else: 
    print "Null"` 

努力:我已經通過各種正則表達式的教程走了,並試圖在各種不同的方式掃描簡單的字符串,如「這是我做的測試」的成功,但如果字符串是有子是行不通的。

新的蟒蛇和正則表達式的任何幫助將不勝感激。

回答

0

這應該工作。

REGEXP:

(\') 

替換:

"'" => "" 

Python代碼:

# coding=utf8 
# the above tag defines encoding for this document and is for Python 2.x compatibility 

import re 

regex = r"(\')" 

test_str = "This 'is' the 'test' I am doing" 

subst = "" 

# You can manually specify the number of replacements by changing the 4th argument 
result = re.sub(regex, subst, test_str, 0, re.MULTILINE) 

if result: 
    print (result) 

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution. 

然後變量=導致

參見:https://regex101.com/r/wuFeG9/3 測試Python代碼:http://ideone.com/0IGz1Q

0
import re 

mystring = "This 'is' the 'test' I am doing" 
searchObj = re.search(r"(.*)'?test'?(.*)", mystring, re.M|re.I) 

if searchObj: 
    print ("searchObj.group() : ", searchObj.group()) 
    print ("searchObj.group(1) : ", searchObj.group(1)) 
    print ("searchObj.group(2) : ", searchObj.group(2)) 
else: 
    print ("Null") 

>>> searchObj.group() : This 'is' the 'test' I am doing 
>>> searchObj.group(1) : This 'is' the ' 
>>> searchObj.group(2) : I am doing