如何在python中匹配字符串后打印所有字符串
a。我有一行如下所示:如何在python中匹配字符串后打印所有字符串,python,regex,python-2.7,Python,Regex,Python 2.7,a。我有一行如下所示: HELLO CMD-LINE: hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red b。我想在-color之后打印字符串 c。我尝试了下面的reg exp方法 for i in range (len(tar_read_sp)): print tar_read_sp[i] wordy = re.findall(r'-
HELLO CMD-LINE: hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red
b。我想在-color
之后打印字符串
c。我尝试了下面的reg exp方法
for i in range (len(tar_read_sp)):
print tar_read_sp[i]
wordy = re.findall(r'-color.(\w+)', tar_read_sp[i], re.M|re.I|re.U)
# print "%s"%(wordy.group(0))
if wordy:
print "Matched"
print "Full match: %s" % (wordy)
print "Full match: %s" % (wordy[0])
# wordy_ls = wordy.group(0).split('=')
# print wordy_ls[1]
# break
else:
print "Not Matched"
但它只打印字符串后面的第一个匹配词,
[“蓝色”、“红色”、“橙色”]
c。但如何在匹配字符串后打印所有字符串?喜欢
['blue',red',green',orange',violet']
并删除重复变量
请分享您的意见和建议,以便打印相同的内容?同意depperm:修复缩进 使用他的正则表达式建议,并结合必要的拆分、重复数据消除和重新排序列表:
wordy = re.findall(r'(?:-color.((?:\w+,?)+))', test_string, re.M|re.I|re.U)
wordy = list({new_word for word in wordy for new_word in word.split(',')})[::-1]
这应该会给你一个像你要求的那样扁平、独特的列表(至少我认为这就是你所说的“删除重复变量”的意思)。我个人倾向于这样做:
import re
tar_read_sp = "hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red"
wordy = re.findall(r'-color.([^\s]+)', tar_read_sp, re.I)
big_list = []
for match in wordy:
small_list = match.split(',')
big_list.extend(small_list)
big_set = list(set(big_list))
print (big_set)
我发现这种方法更容易阅读和更新。我们的想法是获取所有这些颜色匹配,建立一个大的列表,并使用设置来消除重复。我正在使用的正则表达式:
-color ([^\s])+
将在下一个空格中捕获颜色的“小列表”。我有一个不使用正则表达式的解决方案
test_string = 'hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red'
result = []
for colors in [after_color.split(' ')[1] for after_color in test_string.split('-color')[1:]]:
result = result+colors.split(',')
print result
结果是:
['blue'、'red'、'green'、'orange'、'violet'、'red']修复缩进…..尝试
(?:-color.(((?:-w+,?)+)
然后使用拆分()