理论知识需要通过实践巩固。以下精选10个真实场景案例,涵盖常见业务需求,助您彻底掌握mid函数的使用技巧。
案例1:从身份证号提取出生日期
需求:从18位身份证号中提取出生年月日(第7-14位)
Excel
=Mid(A2, 7, 8)
输入身份证号如"110101199003072316",结果为"19900307"
Python
id_number = "110101199003072316"
birth = id_number[6:14]
JavaScript
const idNumber = "110101199003072316";
const birth = idNumber.substr(6, 8);
案例2:从邮箱地址提取用户名
需求:从邮箱"zhangsan@example.com"中提取用户名部分
Excel
=Mid(A2, 1, FIND("@", A2) - 1)
Python
email = "zhangsan@example.com"
username = email.split('@')[0]
username = email[:email.find('@')]
SQL
SUBSTRING(email, 1, CHARINDEX('@', email) - 1)
案例3:从手机号提取运营商编码
需求:从11位手机号中提取前3位(运营商编码)
=Left(A2, 3)
phone = "13812345678"
carrier_code = phone[:3]
const phone = "13812345678";
const carrierCode = phone.substr(0, 3);
案例4:从文件路径提取文件名
需求:从路径"C:UsersDocumentsreport.pdf"中提取文件名"report.pdf"
Excel
=Mid(A2, FIND("", SUBSTITUTE(A2, "", "|", LEN(A2)-LEN(SUBSTITUTE(A2, "", "")))) + 1)
(较复杂,推荐使用TEXTAFTER或RIGHT+FIND组合)
Python
path = "C:\Users\Documents\report.pdf"
filename = path.split("\\")[-1]
import os
filename = os.path.basename(path)
案例5:从日期字符串提取年月日
需求:从"2023-12-25"中分别提取年、月、日
year = Mid(A2, 1, 4)
month = Mid(A2, 6, 2)
day = Mid(A2, 9, 2)
date_str = "2023-12-25"
year = date_str[:4]
month = date_str[5:7]
day = date_str[8:10]
案例6:从日志中提取错误代码
需求:从日志"2023-12-25 14:30:22 ERROR [Code: E001] Connection failed"中提取错误代码"E001"
=Mid(A2, FIND("[", A2) + 1, FIND("]", A2) - FIND("[", A2) - 1)
log = "2023-12-25 14:30:22 ERROR [Code: E001] Connection failed"
start = log.find('[')
end = log.find(']')
error_code = log[start+1:end].split()[-1]
案例7:从URL提取域名
需求:从"https://www.example.com/path/page.html"中提取"example.com"
url = "https://www.example.com/path/page.html"
domain = url.split('//')[-1].split('/')[0]
from urllib.parse import urlparse
parsed = urlparse(url)
domain = parsed.netloc
案例8:从产品编号提取批次信息
需求:产品编号格式为"PROD-2023-12-001",提取批次号"2023-12"
=Mid(A2, FIND("-", A2) + 1, 7)
product_id = "PROD-2023-12-001"
batch = product_id.split("-")[1:3]
batch = product_id.split("-")[1] + "-" + product_id.split("-")[2]
案例9:从文本中提取特定格式的数字
需求:从"订单号:1234567890,金额:¥99.99"中提取金额数字
text = "订单号:1234567890,金额:¥99.99"
amount = text[text.find("¥")+1:].split()[0]
import re
amount = re.search(r"¥(d+.?d)", text).group(1)
案例10:从文本中提取IP地址
需求:从"Server IP: 192.168.1.100 is active"中提取IP地址
text = "Server IP: 192.168.1.100 is active"
import re
ip = re.search(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", text).group()
? 最佳实践:在处理复杂字符串时,考虑结合其他函数(如FIND、LEN、SUBSTITUTE)或正则表达式,以提高灵活性和准确性。