【问题标题】:Regex replace mixed number+strings正则表达式替换混合数字+字符串
【发布时间】:2012-11-07 09:16:43
【问题描述】:

我要删除所有包含数字的单词,例子:

LW23 London W98 String

从上面的字符串中,我唯一想留下的是"London String"。这可以用正则表达式完成吗?

我目前正在使用 Python,但 PHP 代码也可以。

谢谢!

编辑:

这是我现在可以做的:

>>> a = "LW23 London W98 String"
>>> b = a.split(' ')
>>> a
['LW23', 'London', 'W98', 'String']

【问题讨论】:

标签: php python regex


【解决方案1】:

是的,你可以:

result = re.sub(
    r"""(?x) # verbose regex
    \b    # Start of word
    (?=   # Look ahead to ensure that this word contains...
     \w*  # (after any number of alphanumeric characters)
     \d   # ...at least one digit.
    )     # End of lookahead
    \w+   # Match the alphanumeric word
    \s*   # Match any following whitespace""", 
    "", subject)

【讨论】:

  • 谢谢!这是我一直在寻找的解决方案。
【解决方案2】:

您可以尝试使用这种模式的 preg_replace:

/(\w*\d+\w*)/

类似$esc_string = preg_replace('/(\w*\d+\w*)/', '', $old_string);

【讨论】:

    【解决方案3】:

    我不是 100% 确定,这只是对可能解决方案的建议,我不是 python 大师,但如果我看到完整的代码,我可能会更好地了解要做什么。

    我的建议是将字符串的各个部分添加到列表中,弹出每个单词并使用 if 函数来检查数字,如果它们包含数字则将其删除,如果不包含则将它们添加到新列表中,然后,您可以重新排序列表以使单词按适当的顺序排列。

    对不起,如果这没有帮助,我只知道如果遇到问题,我会从这种解决方案开始。

    【讨论】:

    • 由于这是您的第一个答案,我会给您 +1,但对于未来,请发布一些工作代码,而不是描述您将如何做到这一点。
    【解决方案4】:

    你可以用

    匹配一个包含数字的单词
    /\w*\d+\w*/
    

    或者你可以匹配所有没有数字的单词(并保留它们)

    /\w+/
    

    【讨论】:

      【解决方案5】:

      您可以使用正则表达式加理解来做到这一点:

      clean = [w for w in test.split(' ') if not re.search("\d", w)]
      

      words = test.split(' ')
      regex = re.compile("\d")
      clean = [w for w in words if not regex.search(w) ]
      

      输入:

      "LW23 London W98 String X5Y 99AP Okay"
      

      输出:

      ['London', 'String', 'Okay']
      

      【讨论】:

        【解决方案6】:

        取决于我猜的“单词”是什么,但如果我们将空格用作分隔符并且它不必是正则表达式:

        >>> ' '.join(filter(str.isalpha, a.split()))
        'London String'
        

        【讨论】:

        • @SilentGhost 确实如此-很好-我专注于示例字符串-mea culpa
        • 这个问题没有提到任何关于标点符号的内容——例如,LW23, London 会发生什么?只要只涉及空格,这对我来说就是最好的答案。
        猜你喜欢
        • 2018-07-13
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 2013-01-21
        • 1970-01-01
        相关资源
        最近更新 更多