简体   繁体   中英

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.

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 ( []+ ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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