我可以有以下輸入之一:
sma15
sma15.5
sma-15
sma-15.5
foo-15.5usd / or maybe Euro or any other text/character connected to a number
foo-15%
我需要輸出:
sma 15
sma 15.5
foo 15.5 usd
foo 15 %
這可以通過一個簡單的單曲實作regex嗎?我需要它快。
uj5u.com熱心網友回復:
你可以用re.split這個。捕獲組中的部分(...)將包含在結果中。
>>> tests = ['sma15', 'sma15.5', 'sma-15', 'sma-15.5', 'foo-15.5usd', 'foo-15%']
>>> [re.split(r"-?(\d (?:\.\d )?)", x) for x in tests]
[['sma', '15', ''],
['sma', '15.5', ''],
['sma', '15', ''],
['sma', '15.5', ''],
['foo', '15.5', 'usd'],
['foo', '15', '%']]
uj5u.com熱心網友回復:
以下正則運算式識別intand float;
r"([ -]?(?:\d*\.\d*|\d )(?:[Ee][ -]?\d )?)"
它包括一個整體的捕獲組。
測驗:
In [1]: import re
In [2]: numre = re.compile(r"([ -]?(?:\d*\.\d*|\d )(?:[Ee][ -]?\d )?)");
In [3]: re.split(numre, "sma15")
Out[3]: ['sma', '15', '']
In [4]: re.split(numre, "sma15.5")
Out[4]: ['sma', '15.5', '']
In [5]: re.split(numre, "sma-15")
Out[5]: ['sma', '-15', '']
In [6]: re.split(numre, "sma-15.5")
Out[6]: ['sma', '-15.5', '']
In [7]: re.split(numre, "foo-15.5usd")
Out[7]: ['foo', '-15.5', 'usd']
In [8]: re.split(numre, "foo-15.5%")
Out[8]: ['foo', '-15.5', '%']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432908.html
上一篇:如何使用正則運算式匹配特定字串?
