search

Home  >  Q&A  >  body text

python 正则表达式

如何匹配一个前面没有“代理”二字的中文公司如:火狐有限公司
但“火狐代理有限公司”就不匹配。而且“公司”必须得有
我是这样的,但是python里运行并没有成功,
[\u4e00-\u9fa5]+(?<!代理)有{0,1}限{0,1}公司,谢谢

PHPzPHPz2892 days ago281

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-18 09:16:36

    Thank you, I’m not good at regular expressions, but you can try it[u4e00-u9fa5]{1,}.{1,}[^代理]公司, it worked in my test

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:16:36

    python2 needs to use unicode for matching

    regex = ur'^(?!.*代理.*).*公司$'
    print(re.findall(regex, u'火狐代理有限公司'))
    print(re.findall(regex, u'代理有限公司'))
    print(re.findall(regex, u'有限公司'))

    python3 Just remove u and it’s done

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:16:36

    I think you should listen to the advice of the buddy yesterday and use python3.
    I tried it with python3, everything is normal, but I can’t get the result in 2.

    python3 下的运行结果:
    
    >>> re.findall(r'^[^代理].*有?限?公司', "火狐代理有限公司")
    ['火狐代理有限公司']
    >>> re.findall(r'^[^代理].*有?限?公司', "代理有限公司")
    []
    >>> re.findall(r'^[^代理].*有?限?公司', "有限公司")
    ['有限公司']
    >>>

    reply
    0
  • Cancelreply