簡體   English   中英

Python RegEx不匹配,但regexr.com具有相同的表達式

[英]Python RegEx not matching but regexr.com is with same expression

我正在嘗試使用以下代碼來匹配文本est /(?P [0-9] {4})。

使用: https//regexr.com/

它匹配文本,但是在python中,它無法匹配具有相同表達式的相同文本:

[^a-z0-9\/]

這是兩個條件的代碼。 我不確定為什么regEx將在regexr.com中匹配,但在python中不匹配,除非有數字符號。

import os
import re

#no work
if re.match("[^a-z0-9\/]", "test/(?P<year>[0-9]{4})"):
    print "match"
else:
    print "no match"

#works
if re.match("[^a-z0-9\/]", "#test/(?P<year>[0-9]{4})"):
    print "match"
else:
    print "no match"

在您的第一個代碼段中:

if re.match("[^a-z0-9\/]", "test/(?P<year>[0-9]{4})"):
    print "match"
else:
    print "no match"

模式[^a-z0-9\\/]從文本的開頭開始應用。 因此,它失敗了,因為第一個字母是t ,它與模式不匹配。 如果您只想匹配與原始模式相對應的單個字符,則可以嘗試以下模式:

.*[^a-z0-9\/].*

此模式將與您的兩個示例字符串都匹配。 如果您打算使用其他模式,請編輯問題並給我們更多邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM