Axle Max
Axle Max

Reputation: 825

Python Regex exclude matches with letters after /

I have 3 strings as follows:

/foo

/foo/

/foo/bar

If the strings match the first 2 patters I want to return True

If the string has anything after the second forward slash I want to return False

My regex is

re.match(r"^/[a-z]+/?", string)

I can't work out how to exclude the third pattern. Please help. :-)

Upvotes: 0

Views: 288

Answers (2)

blhsing
blhsing

Reputation: 106533

You can use $ to denote the end of a string:

^/[a-z]+/?$

Demo: https://regex101.com/r/v12sWr/1

Upvotes: 0

rassar
rassar

Reputation: 5660

Try this pattern:

^\/[^\/]*\/?$

Explanation:

  • ^: start of word
  • \/: forward slash at beginning
  • [^\/]* any number of non-forward-slash characters. If you want this to just be letters you can make it [a-x]*
  • \/? optional forward slash
  • $ end of word - no more characters

You can try it out with your examples here, and see sample code here.

Upvotes: 1

Related Questions