我想删除所有包含数字的单词,例如:
LW23 London W98 String
从上面的字符串中,我唯一想要保留的是"London String"
. 这可以用正则表达式完成吗?
我目前正在使用 Python,但 PHP 代码也很好。
谢谢!
编辑:
这是我现在可以做的:
>>> a = "LW23 London W98 String"
>>> b = a.split(' ')
>>> a
['LW23', 'London', 'W98', 'String']
是的你可以:
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)
您可以使用以下模式尝试 preg_replace:
/(\w*\d+\w*)/
就像是$esc_string = preg_replace('/(\w*\d+\w*)/', '', $old_string);
取决于我猜的“单词”是什么,但如果我们将空格作为分隔符并且它不必是正则表达式:
>>> ' '.join(filter(str.isalpha, a.split()))
'London String'
我不是 100% 确定,这只是对可能解决方案的建议,我不是 python 大师,但如果我看到完整的代码,我可能会对要做什么有更好的了解。
我的建议是将字符串的各个部分添加到列表中,弹出每个单词并使用 if 函数来检查数字并在它们包含数字时将其删除,如果不包含则将它们添加到新列表中,然后您可以重新排序列表以使单词按适当的顺序排列。
抱歉,如果这没有帮助,我只知道如果遇到问题,我会从这种解决方案开始。
您可以使用正则表达式加理解来做到这一点:
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']
您可以将包含数字的单词与
/\w*\d+\w*/
或者你可以匹配所有没有数字的单词(并保留它们)
/\w+/