【问题标题】:Regex for removing whitespace after a parenthesis python用于在括号 python 后删除空格的正则表达式
【发布时间】:2019-09-27 12:13:49
【问题描述】:

我有如下字符串:

s1 = 'Hello , this is a [ test ] string with ( parenthesis ) .'

我正在尝试删除标点周围的空格,因此它应该如下所示:

s1 = 'Hello, this is a [test] string with (parenthesis).'

我从这里找到了一些代码:How to strip whitespace from before but not after punctuation in python

req = re.sub(r'\s([?,.!"](?:\s|$))', r'\1', text)

我在正则表达式中添加了 ] 和 ) 以包括删除 ] 或 ) 之后的空格

 req = re.sub(r'\s([?,.!\])"](?:\s|$))', r'\1', text)

所以它现在看起来像这样:

s1 = 'Hello, this is a [ test] string with ( parenthesis).'

现在我一直在尝试调整它以删除 [ 或 ( 之前的空格,但我不知道如何。当涉及到正则表达式时我很困惑。

我知道 re.sub() 正在用第一个参数替换第二个参数 (r'\1'),但我不明白 (r'\1') 的实际含义。

任何帮助将不胜感激,

干杯

【问题讨论】:

  • \1 表示第一个捕获匹配组。组是模式中括号包围的内容(在您的模式([?,.!\]) 中)您可以通过执行(?:) (在您的模式(?:\s|$)))中拥有非捕获组
  • re.sub(r'([[(])\s+|\s+([])])(?:\s+(?=[^\w\s]))?', r'\1\2', text) (demo)?

标签: python regex


【解决方案1】:

这可能有助于使用lookbehind & lookahead。

import re

s1 = 'Hello , this is a [ test ] string with ( parenthesis ).'
#print(re.sub(r"(?<=\[|\()(.*?)(?=\)|\])", lambda x: x.group().strip(), s1))
print(re.sub(r'(\s([?,.!"]))|(?<=\[|\()(.*?)(?=\)|\])', lambda x: x.group().strip(), s1))

输出:

Hello, this is a [test] string with (parenthesis).

【讨论】:

  • 您缺少逗号前的空格。
  • @Rakesh 非常感谢你!我将在周末花一些时间学习正则表达式,因为我可以将我的工作提交给我的老板
【解决方案2】:

一种方法是不在括号内捕获开头和结尾的空格,即

 (parens start) some space (capture text) some space (parens close)
      |                          |                         |
   Group 1                   Group 2                    Group 3

匹配 . or , preceded by space using alternation 并将其捕获到单独的组中

([[({])\s*(.*?)\s*([\]\)\}])|\s+([,.])

替换为\1\2\3\4

Regex Demo

【讨论】:

  • @CodeManiac 谢谢!我希望我可以选择两个答案作为我接受的答案,但我会选择第一个以保持公平,但谢谢!
  • @codiearcher 没问题总是乐于提供帮助:)
猜你喜欢
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多