【问题标题】:find string with format '[number]' using regex使用正则表达式查找格式为 '[number]' 的字符串
【发布时间】:2011-05-09 07:08:46
【问题描述】:

我在 django/python 应用程序中有一个字符串,需要在其中搜索 [x] 的每个实例。这包括括号和 x,其中 x 是 1 到几百万之间的任何数字。然后我需要用我自己的字符串替换 x。

也就是说,'Some string [3423] of words and numbers like 9898' 会变成 'Some string [mycustomtext] of words and numbers like 9898'

请注意,只有括号中的数字受到影响。我不熟悉正则表达式,但认为这对我有用吗?

【问题讨论】:

  • 我不想这样做,但我想我可以单独处理这种特殊情况

标签: python regex string replace


【解决方案1】:

正则表达式正是您想要的。它是 Python 中的 re 模块,您需要使用 re.sub,它看起来像:

newstring = re.sub(r'\[\d+\]', replacement, yourstring)

如果您需要做很多事情,请考虑编译正则表达式:

myre = re.compile(r'\[\d+\]')
newstring = myre.sub(replacement, yourstring)

编辑:要重复使用数字,请使用正则表达式组:

newstring = re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring)

还是可以编译的。

【讨论】:

  • \d* 匹配 zero or more digits。你可能想要\d+
  • @Frédéric Hamidi:谢谢,很好。
  • @Thomas K,@Frédéric Hamidi。谢谢,很有帮助。我刚刚意识到我的replacement 实际上应该基于找到的数字。即,如果找到“[2345]”,我可能会将其替换为“[mytext, 2345]”之类的内容。我如何获得找到的号码?
  • 在你的正则表达式中定义一个组,然后在替换字符串中引用它:re.sub(r'\[(\d+)\]',r'[mytext, \1]', yourstring) 编译也应该可以工作。
  • @rsp:好吧,看来这些评论区可以吃反斜杠了。在方括号\\[ \\] 之前应该有一些。我已经更正了主要答案中的最后一个示例。
【解决方案2】:

使用re.sub:

import re
input = 'Some string [3423] of words and numbers like 9898'
output = re.sub(r'\[[0-9]+]', '[mycustomtext]', input)
# output is now 'Some string [mycustomtext] of words and numbers like 9898'

【讨论】:

  • 不要忘记有超过 10 个数字。
  • @Keng:你在说什么?我的代码适用于多位数字。
  • 确实如此,但它只匹配数字 0-9 的数字;有10多个数字。 ;o) blogs.msdn.com/b/oldnewthing/archive/2004/03/09/86555.aspx moserware.com/2008/02/does-your-code-pass-turkey-test.html
  • @Keng:是否匹配 Unicode 数字的选择完全取决于此代码运行的上下文。在您的第一个链接中,Raymond 给出了一个很好的反例,说明为什么您在某些情况下不应该匹配 Unicode 数字。这取决于 OP 匹配的文本类型。
  • 是的......我们都知道墨菲说他也会选择它......哈哈......在凌晨 3 点左右,当车轮从整件事。 80)
【解决方案3】:

既然没有其他人在这里跳,我会给你我的非 Python 版本的正则表达式

\[(\d{1,8})\]

现在在替换部分中,您可以使用“被动组”$n 进行替换(其中 n = 括号中部分对应的数字)。这个是 1 美元

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2020-09-26
    • 2016-03-03
    相关资源
    最近更新 更多