Python Regular

本文介绍了一个使用Python进行正则表达式操作的例子,包括文件读取、字符串匹配等基本功能,并展示了如何从预定义的类别文件中筛选包含特定模式的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.runoob.com/python/python-reg-expressions.html

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os.path
import re

predefClassesFile = "F:\DL\labelImg\data\predefined_classes.txt"

labelHist = []
if os.path.exists(predefClassesFile) is True:
    with codecs.open(predefClassesFile, 'r', 'utf8') as f:
        for line in f:
            line = line.strip()
            if labelHist is None:
                labelHist = [line]
            else:
                labelHist.append(line)

strlist = []
for str in labelHist:
    pattern = re.compile(r'big')
 #   if  re.search(pattern,str):    #查找是否含有该pattern
    if  re.match(pattern,str):      #匹配
        strlist.append(str)
print strlist

### 正则表达式简介 正则表达式是一种强大的工具,用于字符串匹配和操作。然而,在某些情况下其行为可能不如预期那样直观[^1]。 #### 基本字符匹配 最简单的正则表达式由单个字面量字符组成。除了特殊的元字符`*+?()|`外,大多数字符都会按原义进行匹配。为了匹配这些元字符本身,则需要用反斜杠`\`对其进行转义,例如`\+`表示匹配一个实际存在的加号[^3]。 ```python import re pattern = r'\+' # 匹配 '+' 字符 string_with_plus = "The result is 2 + 2." match_result = re.search(pattern, string_with_plus) if match_result: print(f"Found '{match_result.group(0)}' at position {match_result.start()}") # Found '+' at position 14 else: print("No match found.") ``` #### 使用预定义字符集 有时需要查找特定类型的字符而不仅仅是具体的字母或符号。可以利用预定义好的字符集合简化模式构建过程: - `\d`: 数字 `[0-9]` - `\w`: 单词字符(字母、数字及下划线) - `\s`: 空白字符(空格、制表符等) ```python text = "Price: $123.45" price_pattern = r"\$\d+\.\d{2}" # 查找形如$123.45的价格格式 result = re.findall(price_pattern, text) print(result) # ['\$123.45'] ``` #### 定位与边界条件 当希望限定某个子串位于整个输入序列的开头或结尾时,可借助锚点实现精确控制: - `^`: 行首位置 - `$`: 行尾位置 ```python line_starting_with_hello = "^hello world!" starts_with_hello = re.match(r"^hello", line_starting_with_hello) ends_with_world = re.search(r"world!$", line_starting_with_hello) if starts_with_hello and ends_with_world: print("Line matches both start and end criteria.") # Line matches both start and end criteria. ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值