我正在嘗試使用正則運算式只匹配字串中的奇數。我在想的是檢測數字的最后一位數字是否為奇數,但現在我只能找到除最后一位之外的前(n-1)位數字。
例如,以下代碼適用于奇數13,非常完美!但是當轉向 時132,代碼仍然回傳 13,這肯定會失敗。那么,我如何操作代碼并讓它適用于所有以奇數結尾的數字(無論它有多大)?謝謝!
match= '(\s*\d*[13579]\s*)'
print(re.search(match, "The number 13 matches")) #<re.Match object; span=(10, 14), match=' 13 '>
print(re.search(match, "The number 132 matches")) #<re.Match object; span=(10, 13), match=' 13'>
uj5u.com熱心網友回復:
你可以匹配
\d (?!\d)(?<=[13579])
23 132 87 74 101
^^ ^^ ^^^
演示
\d # match one or more digits
(?! # begin negative lookahead
\d # match a digit
) # end negative lookahead
(?<= # begin positive lookbehind
[13579] # match an odd digit
) # end positive lookbehind
(?!\d)可以替換為(?=\D|$),一個肯定的前瞻,斷言匹配后跟一個非數字或在字串的末尾。
uj5u.com熱心網友回復:
用
(?<!\d)\d*[13579](?!\d)
請參閱正則運算式證明。
解釋
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\d* digits (0-9) (0 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
[13579] any character of: '1', '3', '5', '7', '9'
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
) end of look-ahead
蟒蛇代碼:
import re
regex = r"(?<!\d)\d*[13579](?!\d)"
test_str = "The number 13 matches"
matches = re.search(regex, test_str)
if matches is not None:
print(matches.group())
結果:13。
也可以使用單詞邊界:
\b\d*[13579]\b
uj5u.com熱心網友回復:
您可以使用正則運算式,\d [13579](?=\s|$)可以解釋為
\d: 一位或多位[13579]: 1、3、5、7 或 9(?=\s|$): 空格或行尾的正向前瞻斷言
演示:
import re
match= '\d [13579](?=\s|$)'
print(re.search(match, "The number 13 matches"))
print(re.search(match, "The number 132 matches"))
輸出:
<re.Match object; span=(11, 13), match='13'>
None
uj5u.com熱心網友回復:
您可以對小數\d*?進行非貪婪搜索,后跟奇數[13579]和單詞邊界\b。把它放在一起
import re
tests = [("The number 13 matches", True),
("The number 132 matches", False)]
for test, is_match in tests:
match = re.search(r"\d*?[13579]\b", test)
print(repr(test), bool(match), "PASS" if bool(match) == is_match else "FAIL")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323639.html
