我有一个巨大的字符串,实际上包含许多其他子字符串。当我运行我的代码时,它无法正确扫描字符串并返回false值。
目标:我正在尝试在字符串中搜索特定值,并希望将其存储到变量中。
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"`
努力:我已经完成了各种正则表达式的教程并尝试了各种不同的方法,其中扫描简单的字符串如“这是我正在做的测试”是成功但如果字符串有子字符串将无法工作。
python和regex的新功能将非常感谢任何帮助。
答案 0 :(得分: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
答案 1 :(得分: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