【问题标题】:Remove brackets if the content inside is a number如果里面的内容是数字,去掉括号
【发布时间】:2021-11-18 20:06:12
【问题描述】:

如果.isnumeric()里面的内容()有什么办法去掉括号

我确实知道一点 RegEx,但我无法找到使用 RegEx 的方法。

例子:

input = '((1)+(1))+2+(1+2)+((2))'
output = somefunction(input)

这里的输出应该是这样的

(1+1)+2+(1+2)+2

【问题讨论】:

  • 提示:你想用 \d+ 替换表达式 (\d+)...(捕获组,替换为匹配的组内容...)
  • 括号内的内容应该是数字所以这里2是数字但1+1不是
  • @deceze 你能解释一下你的评论吗?
  • 你想得太复杂了。 “如果内容是数字,则尝试删除括号”是一种困难的方法。考虑用匹配的 number 替换任何匹配 “parens number parens” 的字符串。

标签: python regex replace conditional-statements


【解决方案1】:
import re

x = '((1)+(1))+2+(1+2)+((2))'
re.sub(r'(\()([\d*\.]+)(\))', r"\2", x)

"""
or
re.sub(r'\(([\d*\.]+)\)', r"\1", x) #  @deceze
"""

但这会给你 (1+1)+2+(1+2)+(2)

也许可以使用re.subn 来执行此操作,直到替换次数为 0

【讨论】:

  • 感谢您的回答。如果可能的话,您能否通过re.subn 提供答案,这将非常有帮助:)
  • 可以参考docs.python.org/3/library/re.html#re.subn。可以像 re.sub 一样使用 re.subn(在 while 循环中),并使用其返回值 number_of_subs_made 来检查何时停止。
  • 没有必要捕获括号,这只会让这个正则表达式更难阅读。
  • @deceze 已更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 2020-12-13
  • 2022-12-17
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多