首页 > 编程语言 >[950] Python RegEx (re library)

[950] Python RegEx (re library)

时间:2023-11-22 12:55:29浏览次数:37  
标签:RegEx string Python 950 Try Returns characters where match

ref: Python RegEx


A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.

RegEx can be used to check if a string contains the specified search pattern.


RegEx Module

Python has a built-in package called re, which can be used to work with Regular Expressions.

RegEx in Python

After importing the re module, we can start using regular expressions:

RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:

Function Description
findall Returns a list containing all matches
search Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string

Here are some exmaples:

a = "Today is sunny day and I am working now."

r1 = re.findall("\w ", a) 
r2 = re.search("\w ", a) 
r3 = re.split("\w ", a) 
r4 = re.sub("\w ", "==", a) 

print(r1) 
print(r2)
print(r3)  
print(r4) 

# ['y ', 's ', 'y ', 'y ', 'd ', 'I ', 'm ', 'g ']
# <re.Match object; span=(4, 6), match='y '>
# ['Toda', 'i', 'sunn', 'da', 'an', '', 'a', 'workin', 'now.']
# Toda==i==sunn==da==an====a==workin==now.

Metacharacters

Metacharacters are characters with a special meaning:

Character Description Example Try it
[] A set of characters "[a-m]" Try it »
\ Signals a special sequence (can also be used to escape special characters) "\d" Try it »
. Any character (except newline character) "he..o" Try it »
^ Starts with "^hello" Try it »
$ Ends with "planet$" Try it »
* Zero or more occurrences "he.*o" Try it »
+ One or more occurrences "he.+o" Try it »
? Zero or one occurrences "he.?o" Try it »
{} Exactly the specified number of occurrences "he.{2}o" Try it »
| Either or "falls|stays" Try it »
() Capture and group  

Special Sequences

A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:

Character Description Example Try it
\A Returns a match if the specified characters are at the beginning of the string "\AThe" Try it »
\b Returns a match where the specified characters are at the beginning or at the end of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw string")
r"\bain"
r"ain\b"
Try it »
Try it »
\B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw string")
r"\Bain"
r"ain\B"
Try it »
Try it »
\d Returns a match where the string contains digits (numbers from 0-9) "\d" Try it »
\D Returns a match where the string DOES NOT contain digits "\D" Try it »
\s Returns a match where the string contains a white space character "\s" Try it »
\S Returns a match where the string DOES NOT contain a white space character "\S" Try it »
\w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w" Try it »
\W Returns a match where the string DOES NOT contain any word characters "\W" Try it »
\Z Returns a match if the specified characters are at the end of the string "Spain\Z" Try it »

Sets

A set is a set of characters inside a pair of square brackets [] with a special meaning:

Set Description Try it
[arn] Returns a match where one of the specified characters (ar, or n) is present Try it »
[a-n] Returns a match for any lower case character, alphabetically between a and n Try it »
[^arn] Returns a match for any character EXCEPT ar, and n Try it »
[0123] Returns a match where any of the specified digits (012, or 3) are present Try it »
[0-9] Returns a match for any digit between 0 and 9 Try it »
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59 Try it »
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case Try it »
[+] In sets, +*.|()$,{} has no special meaning, so [+] means: return a match for any + character in the string Try it »

 

标签:RegEx,string,Python,950,Try,Returns,characters,where,match
From: https://www.cnblogs.com/alex-bn-lee/p/17848759.html

相关文章

  • 19.python 创建一个本地web服务器
    编写一个server.py文件1importhttp.server2importsocketserver34PORT=800056Handler=http.server.SimpleHTTPRequestHandler78withsocketserver.TCPServer(("",PORT),Handler)ashttpd:9print("Serverstartedatlocalhos......
  • 聪明办法学python
    数据类型:整数(int)         浮点数(float)         布尔值(bool):truefalse         类型(type):print(type(2)) print(type(2.2))  print(type(2<2.2))         isinstance(a,int)常数:truefalsenone......
  • 大数据开发要学什么java还是python?
    在大数据开发领域,Java和Python都是备受青睐的编程语言。它们分别具有各自独特的特点和优势,在大数据处理方面也有不同的应用场景。以下是对Java和Python在大数据开发中的应用、优势以及学习建议的详细描述。Java在大数据开发中的应用和优势1.应用场景Hadoop生态圈:Java广泛......
  • Python在使用pandas时内存使用过大导致服务器宕机,有哪些优化方法?
    当使用pandas处理大规模数据时,内存使用量可能会迅速增加,导致服务器宕机。为了解决这个问题,可以采用以下几个优化方法:数据类型优化:使用更小的数据类型,例如将int64转换为int32或int16,节省内存空间。对于字符串类型,尽量使用'category'类型,它会使用更少的内存。分块处理:使......
  • python+pytest写测试用例后置清理数据操作
    一、teardown_function函数是为了在每个测试函数def执行后进行数据清理。#引入DbConnect类或者确保它已经被定义fromyour_db_moduleimportDbConnectdefteardown_function():try:print("后置操作-做数据清理,把批注通知删掉")db......
  • Java开发者的Python快速进修指南:文件操作
    Python提供的文件操作相对于Java来说,确实简单方便许多。不仅操作简单,代码可读性也相对较高。然而,我们需要注意的不仅仅是文件操作的简单性,还有文件操作的各种模式。在Java中,我们并不经常使用像Python中那样的操作模式。另外,我们还需要注意文件指针的移动。无论是Java还是Python,文......
  • 聪明办法学Python-2023-task01
    task00因为完全按照视频教学傻瓜式操作即可完全学会,这里不做赘述视频链接:【安装】手把手带你配置AI环境_哔哩哔哩_bilibilitask01参考视频链接[Chap1启航]聪明办法学Python第二版_哔哩哔哩_bilibili注释Comment分类:单行注释,使用#开头多行注释,使用'''或"""......
  • python_datetime日期时间
    #!/usr/bin/python3#-*-coding:UTF-8-*-importdatetimeimporttime#时间戳ticks=time.time()print(ticks)#结构体时间{tm_year...}localtime=time.localtime(ticks)print(localtime)#格式化时间strftime=time.asctime(localtime)print(strftime)#获取当前日......
  • 聪明班法学python task1
    Python课程简介Python是一种非常流行的编程语言,是人工智能的主流语言。特点:代码少,比c简单安装Installation安装清单(默认配置即可):Miniconda1.需要激活环境2.更换镜像源【可加快国内资源下载速度】​ Pip换源​ Conda换源VisualStudioCodeGit启航GETTINGSTARTED第......
  • python_字段dict
    字典,类似json#!/usr/bin/python3#-*-coding:UTF-8-*-importjsondata={'name':'abc','age':{'zhousui':7,'xusui':8},'class':'first'}print(data)strJson=json.dumps(data)#json转字符串pr......