Yannick
Yannick

Reputation: 3663

python regex optional match hyphen

How can I write the Regular expressions to accept hyphen but not be mandatory.

Since the folder name can have hyphen in it and sometimes not.

WHen I tried this:

r'^(?P<event_folder_name>[\w-]+)/$/result

It will accept only with hyphen

If I try like this:

r'^(?P<event_folder_name>\w+)

it wont accept it if hyphen is included.

How can I make it that it accept both case.

Thanks.

Upvotes: 1

Views: 1169

Answers (1)

Ion Scerbatiuc
Ion Scerbatiuc

Reputation: 1171

First of all, the $ sign matches the end of the string. Anything after it in the regular expression will be discarded.

Second, your first rule seems ok to me (except the $ in the middle of the expression of course). [\w-]+ means any alphanumeric character (\w) or hyphen (-) one or more times ([]+).

Upvotes: 3

Related Questions