简体   繁体   English

python正则表达式可选匹配连字符

[英]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 ( []+ ). [\\w-]+表示任何字母数字字符( \\w )或连字符( - )一次或多次( []+ )。

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

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