正则表达式替换混合数字+字符串

时间:2012-11-19 12:38:24

标签: php python regex

我想删除所有包含数字的单词,例如:

LW23 London W98 String

从上面的字符串中我唯一想要保留的是"London String"。可以用正则表达式来完成。

我目前正在使用Python,但PHP代码也很好。

谢谢!

编辑:

以下是我现在可以做的事情:

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

6 个答案:

答案 0 :(得分:6)

是的,你可以:

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)

答案 1 :(得分:3)

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

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

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

这样的东西

答案 2 :(得分:3)

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

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

答案 3 :(得分:1)

我不是百分百肯定,这只是对可能的解决方案的建议,我不是蟒蛇大师,但如果我看到完整的代码,我可能会更好地了解待办事项。

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

很抱歉,如果这没有帮助,我只知道如果我遇到问题,这种解决方案就是我要开始的地方。

答案 4 :(得分:1)

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

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']

答案 5 :(得分:0)

您可以将包含数字的单词与

匹配
/\w*\d+\w*/

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

/\w+/
相关问题