V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2021-07-06 09:52:48 +08:00 · 1585 次点击
    这是一个创建于 1025 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2021-07-06 11:37:15 +08:00
    ThirdFlame
        1
    ThirdFlame  
       2021-07-06 10:01:22 +08:00   ❤️ 1
    显然是 python3 \w 的含义 于 py2 的不太一样了啊。 (当然也可能是编码的问题)
    Sylv
        2
    Sylv  
       2021-07-06 10:05:52 +08:00   ❤️ 1
    \w 在 Python 2 里默认只匹配字母或数字或下划线,在 Python 3 里会也匹配包括中文在内的 Unicode 字符。具体请阅读文档。
    Rache1
        3
    Rache1  
       2021-07-06 11:37:15 +08:00   ❤️ 1
    见维基百科「正则表达式」词条。

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


    在 Python3 中,所有字符串都使用 Unicode 表示,所以表现为这样,同样 C# 也是这样,php 中的 mb_ereg 也是
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2885 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 14:31 · PVG 22:31 · LAX 07:31 · JFK 10:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.