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

2024-05-14 21:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

LW23 London W98 String

从上面的字符串中,我只想保留"London String"。这可以用regex实现吗。在

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

谢谢!在

编辑:

我现在可以做的是:

^{pr2}$

Tags: 字符串代码编辑string数字单词regexphp
3条回答

您可以尝试用以下模式替换preg_:

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

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

我想这取决于“单词”是什么,但是如果我们把空格当作分隔符,如果它不一定是正则表达式:

>>> ' '.join(filter(str.isalpha, a.split()))
'London 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)

相关问题 更多 >

    热门问题