删除一切,包括两个单词之间的换行符

时间:2012-12-20 11:30:25

标签: regex string python-2.7

我有以下示例

a = 'cloth <type> length \n
    short \n
    width \n
    </type> close'

想要将a更改为以下内容:

b = 'cloth close'

我用re.DOTALL表达式尝试了re.sub,但它不起作用

3 个答案:

答案 0 :(得分:2)

您可以用空格替换\n,用空格分隔,然后选择列表中的第一个广告最后一个元素。

答案 1 :(得分:1)

如果您尝试删除类型标记之间的内容,可以尝试以下操作:

b = a.gsub(/<type>[\w\s\t\n]+<\/type>/, '').gsub(/\s\s/, ' ')

适用于ruby

答案 2 :(得分:0)

我假设您只想要列表的第一个和最后一个元素以及以下作品:

a = '''cloth <type> length \n
    short \n
    width \n
    </type> close'''
a_split = a.split()                        #Splits on whitespace into tokens
b = [a_split[0], a_split[len(a_split)-1]]  #Take the first and last token