skip to Main Content

I have a model that has some of fields:

class Book(models.Model):
    title = models.CharField(max_length=160, help_text='H1(SEO)',blank=True)
    hashtags = models.TextField(blank=True, validators=[validate_hashtags])

the hashtag inputs should be like:

#sth #sth #sth

in fact I need to have a space after each hashtag except the last one(the last hashtag doesn’t need any space after it). here is my validator function using regex

def validate_hashtags(value):
    string1 = value.split()
    string2 = re.findall("(#\w+ )", value)
    if re.match("^#\w+$", string1[-1]):
        matching_counter = len(string2) + 1
    else:
        matching_counter = len(string2)
    if len(string1) != matching_counter:
        raise ValidationError("please enter # in the correct format")

but it doesn’t work properly, can anyone help me?

2

Answers


  1. You could use this regex to validate the input. Splitting won’t be needed in this case.

    ^(#w+s+)+$

    #sth #sth #sth - Valid
    #sth sth #sth - Invalid
    #sth#sth #sth  - Invalid
    

    Hope it solves the problem.

    Login or Signup to reply.
  2. If there is no space after the last hashtag, you could use match a hashtag followed by 1+ word chars and then repeat a group which matches a space and 1+ word chars.

    ^#w+(?: #w+)*$
    

    Explanation

    • ^ Assert start of string
    • #w+ Match #, then 1+ word chars
    • (?: #w+)* Non capturing group, repeat 0+ times a space, # and 1+ word chars
    • $ Assert end of string

    Regex demo

    If there can be 1+ spaces or tabs after the pattern you could repeat a character class [ t]+:

    ^#w+(?:[ t]+#w+)*$
    

    Regex demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search