Skip to main content
 首页 » 编程设计

python之具有字符和数字的多个字符串的有效正则表达式

2024年10月24日31del

大家好,我是 Python 和 RegEx 的新手。我正在对两者进行试验,并试图获得一个正则表达式来从用户那里提取数据,但考虑到拼写错误等,我希望有不同的输入。所以在下面的代码中,我随机选择了一些我希望用户使用的字符串类型给你一个例子,他们如何输入数据。我只对美元之前或之后的数字感兴趣。例如:

ran = random.randint(1, 7) 
print str(ran) 
if ran == 1: 
    examplestring = "This item costs 20 USD contact 9999999" 
elif ran == 2: 
    examplestring = "This item costs USD 20" 
elif ran == 3: 
    examplestring = "This item costs 20 U.S.D" 
elif ran == 4: 
    examplestring = "This item costs 20 usd" 
elif ran == 5: 
    examplestring = "This item costs 20 Usd call to buy : 954545577" 
elif ran == 6: 
    examplestring = "This item costs 20USD" 
elif ran == 7: 
    examplestring = "This item costs usd20" 
 
regex = re.compile(r'\busd|\bu.s.d\b|\bu.s.d.\b', re.I) 
examplestring = regex.sub("USD", examplestring) 
costs = re.findall(r'\d+.\bUSD\b|\bUSD\b.\d+|\d+USD\b|\bUSD\d+', examplestring) 
cost = "".join(str(n) for n in costs[0]) 
cost = ''.join(x for x in cost if x.isdigit()) 
print cost + " USD" 

使用这些正则表达式,我可以获得我想要的详细信息,即“20 美元”。我的问题是我是否以正确的方式进行操作,是否有可能使代码更好?

请您参考如下方法:

实现方式:

regex = re.compile(r'\b(?=[0-9U])(?:[0-9]+\s*U\.?S\.?D|U\.?S\.?D\s*[0-9]+)\b', re.I) 
 
result = [x.strip(' USD.usd') for x in regex.findall(yourstring)] 

图案细节:

\b         # word boundary 
(?=[0-9U]) # only here to quickly discard word-boundaries not followed 
           # by a digit or the letter U without to test the two branches 
           # of the following alternation. You can remove it if you want. 
 
(?: 
    [0-9]+\s*U\.?S\.?D # USD after 
  |                    # OR 
    U\.?S\.?D\s*[0-9]+ # USD before 
) 
\b 

请注意,对于这两个分支,空格和点是可选的。

然后结果的“USD”部分用一个简单的 strip 删除。它比尝试使用 lookarounds 从匹配结果中排除 USD 更方便(并且可能更快)。