Python利用正則提取字符串中數(shù)字的方法匯總
方法1:最簡單直接的方法(推薦)
import re
text = 'cn_000858'
# 提取所有數(shù)字
numbers = re.findall(r'\d+', text)
print(numbers) # ['000858']
# 如果只需要第一個(gè)匹配結(jié)果
if numbers:
result = numbers[0]
print(result) # '000858'
方法2:使用search提取第一個(gè)數(shù)字
import re
text = 'cn_000858'
# 搜索第一個(gè)數(shù)字序列
match = re.search(r'\d+', text)
if match:
result = match.group()
print(result) # '000858'
方法3:精確匹配’cn_'后的數(shù)字
import re
text = 'cn_000858'
# 匹配'cn_'后面的數(shù)字
match = re.search(r'cn_(\d+)', text)
if match:
result = match.group(1) # group(1)獲取第一個(gè)捕獲組
print(result) # '000858'
方法4:使用findall處理多個(gè)數(shù)字
import re
# 如果字符串中有多個(gè)數(shù)字
text = 'cn_000858_stock_123'
# 提取所有數(shù)字
numbers = re.findall(r'\d+', text)
print(numbers) # ['000858', '123']
# 提取特定位置的數(shù)字
match = re.search(r'cn_(\d+)', text)
if match:
stock_code = match.group(1)
print(f"股票代碼: {stock_code}") # '000858'
方法5:使用split分割提取
import re
text = 'cn_000858'
# 使用下劃線分割,取最后一部分
parts = text.split('_')
result = parts[-1]
print(result) # '000858'
# 或者用正則split
result = re.split(r'[^\d]+', text)[-1]
print(result) # '000858'
方法6:提取并轉(zhuǎn)換為整數(shù)
import re
text = 'cn_000858'
# 提取數(shù)字并轉(zhuǎn)換為整數(shù)(會(huì)去掉前導(dǎo)零)
match = re.search(r'\d+', text)
if match:
number_str = match.group()
number_int = int(number_str)
print(f"字符串: {number_str}, 整數(shù): {number_int}")
# 輸出: 字符串: 000858, 整數(shù): 858
# 如果需要保留前導(dǎo)零,保持字符串形式
result = match.group()
print(f"保留前導(dǎo)零: {result}") # '000858'
方法7:處理多種格式的股票代碼
import re
def extract_stock_code(text):
"""
從各種格式中提取股票代碼
"""
# 匹配多種模式: cn_000858, sh600000, sz000001, 000858等
patterns = [
r'cn_(\d+)', # cn_000858
r'(?:sh|sz)(\d+)', # sh600000, sz000001
r'^(\d{6})$', # 純數(shù)字6位
r'_(\d{6})', # 下劃線后6位數(shù)字
]
for pattern in patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
return match.group(1)
return None
# 測試
test_cases = [
'cn_000858',
'sh600000',
'sz000001',
'000858',
'stock_cn_000858_data',
]
for text in test_cases:
code = extract_stock_code(text)
print(f"{text:20} -> [code]")
方法8:使用命名捕獲組(更清晰)
import re
text = 'cn_000858'
# 使用命名捕獲組
match = re.search(r'cn_(?P<code>\d+)', text)
if match:
code = match.group('code')
print(f"股票代碼: [code]") # '000858'
# 也可以用groupdict()
print(match.groupdict()) # {'code': '000858'}
方法9:批量處理列表
import re
# 批量處理多個(gè)字符串
texts = [
'cn_000858',
'cn_000001',
'sh600000',
'sz000002',
]
# 使用列表推導(dǎo)式
codes = [re.search(r'\d+', text).group() for text in texts if re.search(r'\d+', text)]
print(codes) # ['000858', '000001', '600000', '000002']
# 更安全的方式(處理可能沒有數(shù)字的情況)
codes = []
for text in texts:
match = re.search(r'\d+', text)
if match:
codes.append(match.group())
print(codes)
方法10:完整的股票代碼提取工具
import re
from typing import Optional, List
class StockCodeExtractor:
"""股票代碼提取器"""
@staticmethod
def extract(text: str) -> Optional[str]:
"""
從文本中提取股票代碼
支持格式: cn_000858, sh600000, sz000001, 000858等
"""
if not text:
return None
# 模式列表(按優(yōu)先級排序)
patterns = [
(r'cn_(\d{6})', 1), # cn_000858
(r'(?:sh|sz|hk)(\d{6})', 1), # sh600000, sz000001, hk00700
(r'^(\d{6})$', 1), # 純6位數(shù)字
(r'_(\d{6})', 1), # 下劃線后6位數(shù)字
(r'\b(\d{6})\b', 1), # 單詞邊界的6位數(shù)字
(r'\d+', 0), # 任意數(shù)字(最后備選)
]
for pattern, group_idx in patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
code = match.group(group_idx)
# 驗(yàn)證是否為6位數(shù)字(股票代碼通常是6位)
if len(code) == 6 and code.isdigit():
return code
# 如果不是6位但也沒有其他匹配,返回它
elif group_idx == 0: # 最后一個(gè)模式
return code
return None
@staticmethod
def extract_all(text: str) -> List[str]:
"""
提取文本中所有可能的股票代碼
"""
# 提取所有6位數(shù)字序列
codes = re.findall(r'\b\d{6}\b', text)
return codes
@staticmethod
def validate(code: str) -> bool:
"""
驗(yàn)證股票代碼格式
"""
return bool(re.match(r'^\d{6}$', code))
# 使用示例
if __name__ == "__main__":
extractor = StockCodeExtractor()
test_cases = [
'cn_000858',
'深南電路 cn_000858',
'sh600000',
'sz000001',
'000858',
'股票代碼: 000858',
'hk00700',
]
print("單個(gè)提取:")
for text in test_cases:
code = extractor.extract(text)
is_valid = extractor.validate(code) if code else False
print(f"{text:25} -> {code:10} (有效: {is_valid})")
print("\n批量提取:")
text = "關(guān)注股票: cn_000858, sh600000, sz000001"
codes = extractor.extract_all(text)
print(f"文本: {text}")
print(f"提取的代碼: {codes}")
方法11:處理您的Redis股票數(shù)據(jù)場景
import re
import json
def extract_stock_code_from_redis(data_str):
"""
從Redis讀取的數(shù)據(jù)中提取股票代碼
"""
try:
# 先嘗試解析JSON
data = json.loads(data_str)
# 如果是字典,查找包含代碼的字段
if isinstance(data, dict):
# 嘗試常見的字段名
code_fields = ['code', 'stock_code', 'symbol', 'ts_code']
for field in code_fields:
if field in data:
code = data[field]
# 提取數(shù)字部分
match = re.search(r'\d+', str(code))
if match:
return match.group()
# 如果沒有找到,嘗試從所有值中提取
for value in data.values():
match = re.search(r'\d+', str(value))
if match and len(match.group()) == 6:
return match.group()
# 如果是字符串,直接提取
elif isinstance(data, str):
match = re.search(r'\d{6}', data)
if match:
return match.group()
except json.JSONDecodeError:
# 如果不是JSON,直接從字符串提取
match = re.search(r'\d{6}', data_str)
if match:
return match.group()
return None
# 測試
test_data = [
'{"name": "深南電路", "code": "cn_000858"}',
'{"ts_code": "000858.SZ", "name": "深南電路"}',
'cn_000858',
'000858',
]
for data in test_data:
code = extract_stock_code_from_redis(data)
print(f"{data:40} -> 代碼: [code]")
快速解決方案
針對您的具體需求,最簡單的代碼:
import re # 從 'cn_000858' 提取數(shù)字 text = 'cn_000858' result = re.search(r'\d+', text).group() print(result) # '000858' # 或者一行代碼 result = re.findall(r'\d+', 'cn_000858')[0] print(result) # '000858'
正則表達(dá)式說明
| 模式 | 說明 | 示例 |
|---|---|---|
\d+ | 匹配一個(gè)或多個(gè)數(shù)字 | ‘000858’ |
\d{6} | 匹配恰好6個(gè)數(shù)字 | ‘000858’ |
cn_(\d+) | 匹配’cn_'后的數(shù)字 | ‘000858’ |
(?:sh|sz)(\d+) | 匹配sh或sz后的數(shù)字 | ‘600000’ |
\b\d{6}\b | 單詞邊界的6位數(shù)字 | ‘000858’ |
選擇最適合您場景的方法即可!
以上就是Python使用正則提取字符串中數(shù)字的方法匯總的詳細(xì)內(nèi)容,更多關(guān)于Python正則提取字符串中數(shù)字的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
pytorch和tensorflow計(jì)算Flops和params的詳細(xì)過程
這篇文章主要介紹了pytorch和tensorflow計(jì)算Flops和params,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
Ubuntu 下 vim 搭建python 環(huán)境 配置
這篇文章主要介紹了Ubuntu 下 vim 搭建python環(huán)境配置,需要的朋友可以參考下2017-06-06
python yolo混合文件xml和img整理/回顯yolo標(biāo)注文件方式
本文介紹了如何根據(jù)XML文件中的標(biāo)簽順序進(jìn)行索引轉(zhuǎn)換,并提供了一種自定義標(biāo)簽轉(zhuǎn)格式的方法,以回顯YOLO標(biāo)注文件2026-01-01
pandas實(shí)現(xiàn)數(shù)據(jù)concat拼接的示例代碼
pandas.concat用于合并DataFrame或Series,本文主要介紹了pandas實(shí)現(xiàn)數(shù)據(jù)concat拼接的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解一下2025-06-06
Python基于SciPy庫實(shí)現(xiàn)統(tǒng)計(jì)分析與建模
SciPy是一個(gè)強(qiáng)大的Python庫,提供了豐富的科學(xué)計(jì)算和數(shù)據(jù)分析工具,本文我們將探討如何使用Python和SciPy庫進(jìn)行統(tǒng)計(jì)分析和建模,感興趣的可以學(xué)習(xí)一下2023-06-06
5道關(guān)于python基礎(chǔ) while循環(huán)練習(xí)題
這篇文章主要給大家分享的是5道關(guān)于python基礎(chǔ) while循環(huán)練習(xí)題,無論學(xué)習(xí)什么語言,練習(xí)都是必不可少的,下面文章的練習(xí)題挺精湛的,需要的朋友可以參考一下2021-11-11
python借助pandas操作excel的常見場景及進(jìn)階技巧詳解
Python的Pandas庫是處理Excel文件的強(qiáng)大工具,它提供了簡潔高效的接口來讀取、處理和分析表格數(shù)據(jù),本文為大家整理了Pandas操作Excel的核心方法,常見場景及進(jìn)階技巧,有需要的小伙伴可以了解下2026-01-01

