Python 2.6+ str.format() and regular expressions

后端 未结 2 1507
醉梦人生
醉梦人生 2021-01-07 17:59

Using str.format() is the new standard for formatting strings in Python 2.6, and Python 3. I\'ve run into an issue when using str.format() with reg

相关标签:
2条回答
  • 2021-01-07 18:26

    Per the documentation, if you need a literal { or } to survive the formatting opertation, use {{ and }} in the original string.

    '^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com')
    
    0 讨论(0)
  • 2021-01-07 18:30

    you first would need to format string and then use regex. It really doesn't worth it to put everything into a single line. Escaping is done by doubling the curly braces:

    >>> pat= '^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com')
    >>> pat
    '^(w{3}\\.)?([0-9A-Za-z-]+\\.){1}delivery.com$'
    >>> re.match(pat, str1)
    

    Also, re.match is matching at the beginning of the string, you don't have to put ^ if you use re.match, you need ^ if you're using re.search, however.

    Please note, that {1} in regex is rather redundant.

    0 讨论(0)
提交回复
热议问题