• . 匹配除换行符以外的任意字符。
  • ^ 匹配字符串的开头。
  • $ 匹配字符串的结尾。
  • * 匹配前一个字符零次或多次。
  • + 匹配前一个字符一次或多次。
  • ? 匹配前一个字符零次或一次。非贪婪匹配,只要后面的满足就停止
  • {n} 匹配前一个字符恰好 n 次。
  • {n,} 匹配前一个字符至少 n 次。
  • {n,m} 匹配前一个字符至少 n 次,至多 m 次。
  • [] 匹配中括号内的任意一个字符。
  • () 创建一个组。
  • \d 匹配一个数字。
  • \w 匹配一个单词字符(字母、数字、下划线)。
  • \s 匹配一个空白字符(空格、制表符、换行符)。

' ' 这里面的都是规则

match

1
2
3
4
5
6
7
pattern = r"hello"
text = "hello world"
match = re.match(pattern, text)
if match:
    print("Match found:", match.group())
else:
    print("No match")

  

search

1
2
3
4
5
6
7
pattern = r"world"
text = "hello world"
search = re.search(pattern, text)
if search:
    print("Found:", search.group())
else:
    print("Not found")

  

findall

1
2
3
4
pattern = r"ab"
text = "ababab"
matches = re.findall(pattern, text)
print(matches)

  

sub

1
2
3
4
pattern = r"apple"
text = "apple banana apple cherry"
new_text = re.sub(pattern, "orange", text)
print(new_text)

  

dataframe里使用

正则写在一个函数里,调用函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pandas as pd
import re
 
data = {'200': ['abc (123)', 'def (456)', 'ghi (789)']}
df = pd.DataFrame(data)
 
# 定义一个函数来处理括号内的内容
def remove_content_in_parentheses(text):
    return re.sub(r'\([^)]*\)', '', text)
 
# 对'200'列应用函数
df['200'] = df['200'].apply(remove_content_in_parentheses)
 
# 输出处理后的DataFrame
print(df)

  

demo:

去掉() 里的内容

1
2
3
4
5
6
7
8
import re
 
txt = "目前关于这一疾病状态(current disease state)的临床数据(limited clinical data)仍然有限。通过观察不同患者群体(patient group)的临床特征(clinical characteristics)"
 
# 使用正则表达式去除括号内的英文内容
cleaned_txt = re.sub(r'(.*?)', '', txt)
 
print(cleaned_txt)

  

posted on   黑逍逍  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2023-03-12 如何使用



点击右上角即可分享
微信分享提示