【问题标题】:I need to extract domain from email but i get @domain.com i dont need the @ at the start of the domain我需要从电子邮件中提取域,但我得到@domain.com 我不需要域开头的@
【发布时间】:2015-07-10 06:07:58
【问题描述】:

我需要从电子邮件中提取域,但我得到了@domain.com。我不需要域开头的@

class ExtractDomain(webapp2.RequestHandler):
  def get(self):

    user = (str(users.get_current_user().email()))
    domain = re.search("@[\w.]+", user)
    thisdomain = domain.group()


    template_values = {'user': user, 'thisdomain':thisdomain}
    template = jinja2_env.get_template('templates/domain.html')
    self.response.out.write(template.render(template_values))

【问题讨论】:

    标签: regex python-2.7 google-app-engine-python


    【解决方案1】:

    你的正则表达式是@[\w.]+,它匹配@words.com,你所要做的就是对@做一些事情,所以它不在你的结果中。

    解决方案 1:往后看

    Lookbehinds 测试前面的字符是否匹配,而不改变结果。 (?<=@)[\w.]+

    解决方案 2:捕获组

    你可以指定你想要的部分,在你的情况下 @([\w.]+) 在括号中,然后用 $1 调用它。但是,这需要对您的代码稍作修改。

    对于第一个解决方案,您只需要更改正则表达式所在的行:domain = re.search("(?<=@)[\w.\-]+", user) 添加了\- 以便处理一些多字域名,而不是问题所必需的。

    【讨论】:

    • @TJ 不需要改变太多,更新我的答案
    • @TJ 作为旁注,您可能希望将- 添加到您的角色类(?<=@)[\w.\-]+ 中,以便正确处理test@some-domain.com
    【解决方案2】:

    使用捕获括号:

    1- domain = re.search( "@([\w.]+)", user ).group(1)
    

    或者之后去掉第一个字符:

    2- domain = domain[1:]
    

    不确定这是否是正确的方法(不要对 python 做太多),但它有效。

    【讨论】:

      猜你喜欢
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 2018-06-03
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多