从开头和结尾删除字符或仅删除行尾

时间:2010-11-06 15:25:57

标签: python regex

我想使用正则表达式从字符串中删除一些符号,例如:

==(在一行的开头和结尾都出现),

*(仅在一行的开头)。

def some_func():
    clean = re.sub(r'= {2,}', '', clean) #Removes 2 or more occurrences of = at the beg and at the end of a line.
    clean = re.sub(r'^\* {1,}', '', clean) #Removes 1 or more occurrences of * at the beginning of a line.

我的代码出了什么问题?表达似乎是错误的。如果字符/符号位于行的开头或结尾(有一个或多个匹配项),如何删除它?

5 个答案:

答案 0 :(得分:6)

如果您只想从开头和结尾删除字符,可以使用string.strip()方法。这会给出一些像这样的代码:

>>> s1 = '== foo bar =='
>>> s1.strip('=')
' foo bar '
>>> s2 = '* foo bar'
>>> s2.lstrip('*')
' foo bar'

strip方法从字符串的开头和结尾删除参数中给出的字符,ltrip仅从开头删除它们,而rstrip仅从字符串中删除它们端。

如果你真的想使用正则表达式,它们看起来像这样:

clean = re.sub(r'(^={2,})|(={2,}$)', '', clean)
clean = re.sub(r'^\*+', '', clean)

但恕我直言,使用strip / lstrip / rstrip最适合您的目标。

编辑:根据Nick的建议,这是一个可以在一行中完成所有这些工作的解决方案:

clean = clean.lstrip('*').strip('= ')

(一个常见的错误是认为这些方法按照它们在参数中给出的顺序删除字符,事实上,参数只是一个要删除的字符序列,无论它们的顺序如何,这就是为什么{{ 1}}将从开头和结尾删除每个'='和'',而不仅仅是字符串'='。)

答案 1 :(得分:3)

你的正则表达式中有额外的空格。即使是空间也算作一个角色。

r'^(?:\*|==)|==$'

答案 2 :(得分:0)

首先,你应该注意“{”之前的空格......那些是有意义的,所以你的例子中的量词适用于空间。

要仅在开始或结束时删除“=”(两个或更多),您还需要一个不同的正则表达式...例如

clean = re.sub(r'^(==+)?(.*?)(==+)?$', r'\2', s)

如果你没有放“^”或“$”,表达式可以匹配任何地方(即使在字符串的中间)。

答案 3 :(得分:0)

而不是代替但保持? :

tu = ('======constellation==' , '==constant=====' ,
      '=flower===' , '===bingo=' ,
      '***seashore***' , '*winter*' ,
      '====***conditions=**' , '=***trees====***' , 
      '***=information***=' , '*=informative***==' )

import re
RE = '((===*)|\**)?(([^=]|=(?!=+\Z))+)'
pat = re.compile(RE)

for ch in tu:
    print ch,'  ',pat.match(ch).group(3)

结果:

======constellation==    constellation
==constant=====    constant
=flower===    =flower
===bingo=    bingo=
***seashore***    seashore***
*winter*    winter*
====***conditions=**    ***conditions=**
=***trees====***    =***trees====***
***=information***=    =information***=
*=informative***==    =informative***

你真的想要吗

==== *** condition = **给出条件= **?

*** ====百==== ***给百分==== ***?

开头? * *

答案 4 :(得分:0)

我认为以下代码可以完成这项工作:

tu = ('======constellation==' , '==constant=====' ,
      '=flower===' , '===bingo=' ,
      '***seashore***' , '*winter*' ,
      '====***conditions=**' , '=***trees====***' , 
      '***=information***=' , '*=informative***==' )

import re,codecs

with codecs.open('testu.txt', encoding='utf-8', mode='w') as f:
    pat = re.compile('(?:==+|\*+)?(.*?)(?:==+)?\Z')
    xam = max(map(len,tu)) + 3
    res = '\n'.join(ch.ljust(xam) + pat.match(ch).group(1)
                    for ch in tu)
    f.write(res)
    print res

当我在我之前的帖子中写下RE时,我的大脑在哪里? ØO! 非贪心量词。*?在== + \ Z之前是真正的解决方案。

相关问题