[英]regular expression to match an odd number in a string
我正在嘗試使用正則表達式只匹配字符串中的奇數。 我在想的是檢測數字的最后一位數字是否為奇數,但現在我只能找到除最后一位之外的前(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'>
你可以匹配
\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|$)
,這是一個肯定的前瞻,斷言匹配后跟一個非數字或在字符串的末尾。
用
(?<!\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
您可以使用正則表達式\\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
您可以對小數\\d*?
進行非貪婪搜索\\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")
使用前瞻檢查奇數數字后面是否沒有另一個數字:
match = '\d*[13579](?!\d)'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.