简体   繁体   中英

Regex matching alphanumeric with special characters

I am trying to form an url in Django url pattern .

   url(r'^reports/(?P<bu>\w+|\W)/$', \
                LrsReportView.as_view(), name="elearning.lrsreports.region"),  

The bu can be a string or string alphanumeric or alphanumeric with special character (except /)

But the above url is showing error for

NoReverseMatch: Reverse for 'elearning.lrsreports.region' with arguments '(u'Lawn&Garden',)' and keyword arguments '{}' not found.

From the error I understood is this regex is not accepting the string having special character

Please help me out what might wrong here .

Your current RegEx will match:

  • A string of one or more letters, numbers and/or underscores: [A-Za-z0-9_]+

OR

  • A SINGLE character that is NOT a letter, number or underscore. [^A-Za-z0-9_]

You probably need something more like:

(?P<bu>[\w-]+)

This will match letters, numbers, underscore and hyphens. Add any other special characters you want as well (inside the square brackets). Remeber certain characters need escaping with \\ before them.

Try this-

/^(?=. [az])(?=. [AZ])(?=. \\d)(?=. (_|[^\\w])).+$/

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