Search code examples
pythonregexdjangoslug

Django: autoslug -> custom slugifier


I have a prob. I'm trying to create a custom slugify functiom. I use django.autoslug. Due to autoslug documentation I was able to create a custom slugifier, but it needs to be improved and I do not know how do I realize that.

So I have a string (book title) i.e. .NET Framework 4.0 with C# & VB in VisualStudio 2010. I want to slugify it so that it looks like this: dotnet-framework-4point0-with-cshapr-and-vb-in-visualstudio-2010

My current function looks like this:

def custom_slug(value, *args, **kwargs):
    associations_dict = {'#':'sharp', '.':'dot', '&':'and'}
    for searcg_char in associations_dict.keys():
       if search_char in value:
          value = value.replace(search_char, associations_dict[search_char])
    return def_slugify(value)

As you can see, my function replaces all dots . with 'dot'. So my string will be changed into dotnet-framework-4dot0-with-csharp-and-vb-in-visualstudio-2010

I suggest, I should use RegEx, but I don't know how to do this and how do I replace matched string with right 'dot/point-replacement'

Ideas ?!

P.S. Sorry for bad English


Solution

  • import re
    point = re.compile( r"(?<=\d)\.(?=\d)" )
    point.sub( value, "point" )
    

    to change the . s that should be "point" , and then do str.replace to change the others.

    Explanation

    point matches a . which is sandwiched between two digits.

    (?<=spam)ham(?=eggs) is a (positive) lookaround. It means "match ham, as long as it is preceded by spam and followed by eggs". In other words, it tells the regex engine to "look around" the pattern that it is matching.