简体   繁体   English

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

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

I'm trying to use the following code to match the text est/(?P[0-9]{4}). 我正在尝试使用以下代码来匹配文本est /(?P [0-9] {4})。

using: https://regexr.com/ 使用: https//regexr.com/

it matches the text, however in python it fails to match the same text with the same expression: 它匹配文本,但是在python中,它无法匹配具有相同表达式的相同文本:

[^a-z0-9\/]

Here is the code with both conditions. 这是两个条件的代码。 I'm not sure why the regEx will match in regexr.com but not in python unless there is a number sign. 我不确定为什么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"

In your first code snippet: 在您的第一个代码段中:

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

The pattern [^a-z0-9\\/] is being applied starting at the beginning of the text. 模式[^a-z0-9\\/]从文本的开头开始应用。 Hence, it fails because the first letter is t , which does not match the pattern. 因此,它失败了,因为第一个字母是t ,它与模式不匹配。 If you intend to just match a single character corresponding to your original pattern, then you may try the following pattern: 如果您只想匹配与原始模式相对应的单个字符,则可以尝试以下模式:

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

This pattern will match for both of your example strings. 此模式将与您的两个示例字符串都匹配。 If you intend to use another pattern, then edit your question and give us more logic. 如果您打算使用其他模式,请编辑问题并给我们更多逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM