带有nonASCII字符的正则表达式模式

2024-04-24 22:11:51 发布

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

问题摘要

我有这个regex python代码:

lst =[' ', 'US$170.8980\xa0billion', '[2]', '\xa0(2018)']
for i in lst:
    pat = re.compile(r'([\x1F-\x7F]+).+(\d+)')
    results=pat.search(i)
    print(results)

我用正则表达式模式得到这个输出:

None
<_sre.SRE_Match object; span=(0, 11), match='US$170.8980'>
None
<_sre.SRE_Match object; span=(1, 6), match='(2018'>

期望输出

理想情况下,我希望得到以下输出:

[US$170.8980-billion-(2018)]

Tags: 代码noneobjectmatchresultsregexusxa0
2条回答

这对我很有用:

string = 'US$170.8980\xa0billion'
pat = ''.join(re.findall('([a-zA-Z0-9$.])', string))

适应

lst = [' ', 'US$170.8980\xa0billion', '[2]', '\xa0(2018)']
for i in lst:
    pat = ''.join(re.findall('([a-zA-Z0-9$.\s])', i))
    print(pat)

备选方案:

(re.findall('([^�])', i)

也许,这个表达可能和你想的很接近

import re

lst =[' ', 'US$170.8980\xa0billion', '[2]', '\xa0(2018)']

output =''
for index,item in enumerate(lst):
    item = item.strip()
    if re.match('\[\d+\]',item) == None:
        if index == len(lst)-1:
            output +='-'
        output += re.sub(r'[^ -~]','-', item)

print(output)

但不确定。你知道吗

输出

US$170.8980-billion-(2018)

相关问题 更多 >