python正则表达式在标点符号和字母之间插入空格

时间:2013-12-20 14:29:50

标签: python regex string

我认为最好的方法是使用正则表达式,但我不知道该怎么做。我试图解析一个字符串,并在字母和标点之间放置一个空格。我想把标点符号放在一起。举个例子,如果我有字符串

“是!!!”

我想以

结束

“是”,“!!!”。

如果我有字符串

!!! N00bs,

我想以

结束

“!!!”,“N00bs”

这可能吗?做这个的最好方式是什么?现在我正在解析每个字母,这是一种愚蠢的方式。

感谢您的帮助。

3 个答案:

答案 0 :(得分:10)

类似的东西:

txt = re.sub( r'([a-zA-Z])([,.!])', r'\1 \2', '!!!this, .is, .a .test!!!' )

您可以切换其他方向的订单

re.sub( r'([,.!])([a-zA-Z])', r'\1 \2', txt )

可能你也可以让它在一个正则表达式中工作

答案 1 :(得分:0)

如果您只想添加空格,可以使用替换?

x = x.replace('!',' ')

您可能需要使用更多替换来删除标点符号和标点符号之间的空格。

答案 2 :(得分:0)

我会用:

(.+)\b(.+)

适用于yes!!!!!!N00bs

<强>解释

The regular expression:

(?-imsx:(.+)\b(.+))

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  (                        group and capture to \1:
----------------------------------------------------------------------
    .+                       any character except \n (1 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
  )                        end of \1
----------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
----------------------------------------------------------------------
  (                        group and capture to \2:
----------------------------------------------------------------------
    .+                       any character except \n (1 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
  )                        end of \2
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------