博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

正则表达是常用语法测试

Posted on 2020-10-09 17:47  cmzchxj  阅读(75)  评论(0编辑  收藏  举报

试下

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a = re.sub(r'hello', 'i love the', 'hello world')
print(a)
SyntaxError: multiple statements found while compiling a single statement
>>> a = re.sub(r'hello', 'i love the', 'hello world')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a = re.sub(r'hello', 'i love the', 'hello world')
NameError: name 're' is not defined
>>> import re
>>> a = re.sub(r'hello', 'i love the', 'hello world')
>>> print(a)
i love the world
>>> phone = "2004-959-559 # 这是一个国外电话号码"
>>> re.sub(r'#.*$', "", phone)
'2004-959-559 '
>>> re.sub(r'#.*$', "111", phone)
'2004-959-559 111'
>>> re.sub(r' ', "", phone)
'2004-959-559#这是一个国外电话号码'
>>> re.sub(r'#.*$', "", re.sub(r' ', "", phone))
'2004-959-559'
>>>