V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
karlxu
V2EX  ›  Python

请教一个 Python 正则问题,相同代码运行出来结果不一样了

  •  
  •   karlxu · Jul 6, 2021 · 2107 views
    This topic created in 1760 days ago, the information mentioned may be changed or developed.
    datay='Python 是很受欢迎的编程语言 Python'
    pattern9='[a-zA-Z]+' #字符集的范围 + 号 代表 前导字符模式出现 1 次以上
    res=re.sub(pattern9,'Java',datay)
    print(res)

    datas='Python 是很受欢迎的编程语言 Python'
    pattern1='\w+'
    ww=re.sub(pattern1,'java',datas) #sub 不能用 group()函数,因为返回的是一个元组
    print(ww)


    上面这段在 Python2.7 运行后 print 是一致的:


    但是在 Python3.9 运行后是不一样的:


    为什么第二种方法出来的结果只是 java,连中文部分都没有了?
    3 replies    2021-07-06 11:37:15 +08:00
    ThirdFlame
        1
    ThirdFlame  
       Jul 6, 2021   ❤️ 1
    显然是 python3 \w 的含义 于 py2 的不太一样了啊。 (当然也可能是编码的问题)
    Sylv
        2
    Sylv  
       Jul 6, 2021   ❤️ 1
    \w 在 Python 2 里默认只匹配字母或数字或下划线,在 Python 3 里会也匹配包括中文在内的 Unicode 字符。具体请阅读文档。
    Rache1
        3
    Rache1  
       Jul 6, 2021   ❤️ 1
    见维基百科「正则表达式」词条。

    \w 匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”。注意 Unicode 正则表达式会匹配中文字符。


    在 Python3 中,所有字符串都使用 Unicode 表示,所以表现为这样,同样 C# 也是这样,php 中的 mb_ereg 也是
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2647 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 03:14 · PVG 11:14 · LAX 20:14 · JFK 23:14
    ♥ Do have faith in what you're doing.