Python正则表达式匹配数字,但忽略包含数字的单词(即N95和3D)

2024-09-27 17:58:16 发布

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

我有不同长度的多行字符串和需要去除数字的内容,但我需要保留合法包含数字的单词

例如,这个完全由字符串组成(请注意换行符):

"3 3D Apple car 19.74 N95 8.0 -8.0 .1 7,000 1. table
AH4R99JKH
75"

应用正则表达式后,应符合以下要求:

"3D Apple car N95 table AH4R99JKH"

我曾多次尝试用正则表达式来识别“实数”,但都失败了。有人有什么建议吗


Tags: 字符串内容appletable数字单词car建议
2条回答

这是我想到的

your_string = """3 3D Apple car 19.74 N95 8.0 -8.0 .1 7,000 1. table
AH4R99JKH
75"""
result = ' '.join(re.findall('[a-zA-Z]+[0-9A-Z]+|[0-9A-Z]+[a-zA-Z]+|[a-zA-Z]+', your_string))
#'[a-zA-Z]+[\w]+|[\w]+[a-zA-Z]+|[a-zA-Z]+' same regex but more compact

这将为您提供:

3D Apple car N95 table AH4R99JKH

你可以列一个包含所有字母的列表,并进行核对

这段代码帮助您做到这一点

letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string = "3 3D Apple car 19.74 N95 8.0 -8.0 .1 7,000 1. table AH4R99JKH 75"
str_list = string.split()
last_t = ''
for item in str_list:
    check = False
    for i in item:
        if i in letter:
            check = True
    if check == True:
        last_t += f'{item} '
        
print(f"{last_t.strip()}")

#response => "3D Apple car N95 table AH4R99JKH"

相关问题 更多 >

    热门问题