1

I'm trying to use the following code to match the text est/(?P[0-9]{4}).

using: https://regexr.com/

it matches the text, however in python it fails to match the same text with the same expression:

[^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.

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"
Grant Zukel
  • 1,153
  • 2
  • 24
  • 48
  • 1
    Your regex pattern bears little resemblance to the text you are trying to match. Can you let us know what you are trying to do here? – Tim Biegeleisen Feb 21 '18 at 01:41
  • Your pattern will match a single character at the beginning of the string that is NOT a (lower case letter OR a digit OR a slash). – wwii Feb 21 '18 at 01:45
  • 1
    Possible duplicate of [What is the difference between re.search and re.match?](https://stackoverflow.com/questions/180986/what-is-the-difference-between-re-search-and-re-match) – ctwheels Feb 21 '18 at 01:51
  • You need to use `search()` instead of `match()`. The latter anchors to the start of the string, so your regex becomes `^[^a-z0-9\/]`. – ctwheels Feb 21 '18 at 01:51

1 Answers1

1

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. Hence, it fails because the first letter is t, which does not match the pattern. 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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360