我正在嘗試創建一個正則運算式,其中如果找到某個字符集,它不應該回傳任何匹配項,但如果找不到該字符集,那么它應該回傳由正則運算式的其余部分找到的匹配項。到目前為止的例子:
re.search('^(?:(?!>).) $','>Jack Sparrow/Harry>Potter')
>>> No match found as > present which is what I wanted
re.search('(^(?:(?!>).) $)(/Harry)','Jack Sparrow/Harry Potter')
>>> No match found but I was expecting it to return true as > is not there while '/Harry' is
我究竟做錯了什么?
uj5u.com熱心網友回復:
如果要確保字串不包含<并且包含/Harry,則需要匹配整個字串以確保它沒有<字符。
所以你可以使用
re.fullmatch(r'[^>]*?/Harry[^>]*', text)
re.search(r'^[^>]*?/Harry[^>]*$', text)
re.match(r'[^>]*?/Harry[^>]*$', text)
詳情:
^- 字串的開始[^>]*?- 除了>盡可能少的任何零個或多個字符/Harry- 固定字串[^>]*- 零個或多個字符,而不是>盡可能多的字符$- 字串結束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406630.html
標籤:
上一篇:區分大小寫的名稱檢查器
