3

I want to write a template tag to replace spaces,tabs,new lines,commas,underscores with dashes to make a SEO friendly URL:

re.sub('\s+', '-', str)

this line of code replace spaces with dash and:

re.sub('(?<=[,.?!\t\n ])+', '-', str)

this line of code should replace ?<=[,.?!، and space with dash, but it doesn't.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Asma Gheisari
  • 5,794
  • 9
  • 30
  • 51

1 Answers1

5

Have you considered using the built in slugify filter?

The problem with your second expression is you are using a positive lookbehind (?<=).

From regular-expressions.info:

"Zero-width positive lookbehind. Matches at a position if the pattern inside the lookahead can be matched ending at that position (i.e. to the left of that position).

The following is probably what you were trying to do:

re.sub('[,.?!\t\n ]+', '-', s)

This is replacing any sequence of characters ,.?!\t\n with a single dash.

Hamish
  • 22,860
  • 8
  • 53
  • 67