Appearance
实现 文本信息批量提取 工具
分类:general | 标签:提取、正则、文本 批量提取电话/邮箱/URL/IP/身份证/日期
2.1 功能说明
批量提取电话/邮箱/URL/IP/身份证/日期
2.1.1 使用指南
功能说明
从大段文本中批量提取手机号、邮箱、网址、IPv4、身份证号、日期,自动去重、排序并可导出。
使用场景
运营数据清洗、客户信息整理、爬虫结果处理、日志分析。
2.2 代码实现
2.2.1 组件结构
本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-input、el-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。
2.2.2 核心逻辑概览
<script setup> 中定义的主要函数/方法:
run()copyAll()download()
2.2.3 关键实现代码
以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。
vue
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ToolPageShell from '@/components/ToolPageShell.vue'
const keys = ['phone', 'email', 'url', 'ip', 'idcard', 'date']
const labels = { phone: '手机号', email: '邮箱', url: '网址', ip: 'IPv4', idcard: '身份证号', date: '日期' }
const sel = ref({ phone: true, email: true, url: true, ip: false, idcard: false, date: false })
const dedupe = ref(true), sort = ref(false), lineMode = ref(false)
const text = ref('')
const result = ref('')
const counts = ref('')
const PATTERNS = {
phone: /(?<![\d])1[3-9]\d{9}(?![\d])/g,
email: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,
url: /(?:https?:\/\/|www\.)[^\s"'<>]+/gi,
ip: /(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)/g,
idcard: /[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]/g,
date: /\b\d{4}[-/年.](0?[1-9]|1[0-2])[-/月.](0?[1-9]|[12]\d|3[01])\b/g
}
function run() {
const input = text.value || ''
if (!input.trim()) { result.value = ''; counts.value = ''; ElMessage.info('请输入文本'); return }
let found = []
if (lineMode.value) {
const lines = input.split(/\r?\n/)
for (const line of lines) {
let hit = false
for (const k of keys) if (sel.value[k] && PATTERNS[k].test(line)) hit = true
if (hit) found.push(line)
for (const k of keys) PATTERNS[k].lastIndex = 0
}
} else {
for (const k of keys) {
if (!sel.value[k]) continue
const m = input.match(PATTERNS[k]) || []
found.push(...m)
PATTERNS[k].lastIndex = 0
}
}
if (dedupe.value) found = [...new Set(found)]
if (sort.value) found.sort((a, b) => a.localeCompare(b, 'zh'))
result.value = found.join('\n')
counts.value = `共 ${found.length} 项` + (dedupe.value ? '(已去重)' : '')
}
function copyAll() {
if (result.value) navigator.clipboard?.writeText(result.value).then(() => ElMessage.success('已复制'))
}
function download() {
if (!result.value) return
const blob = new Blob([result.value], { type: 'text/plain;charset=utf-8' })
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = 'extracted.txt'
a.click()
URL.revokeObjectURL(a.href)
}2.3 效果截图
