需求
根据需求匹配数据并提取所需数据
处理前
const textList = [
'@[]', // 不匹配
'@[123]', // 不匹配
'@asd[133]', // 匹配
'@阿里巴巴(杭州)(西湖)[546789][12113][12113][12113][12113][12113][12113]', // 匹配
'@阿里巴巴(杭州)(西湖)[12113]', // 匹配
'@阿里巴巴[444]' // 匹配
]
处理后
[
{ name: 'asd', id: '133' },
{ name: '阿里巴巴(杭州)(西湖)', id: '546789' },
{ name: '阿里巴巴(杭州)(西湖)', id: '12113' },
{ name: '阿里巴巴', id: '444' }
]
解决
方法一
// 确定处理函数
const getFormatTextList = (textList) => {
const regex = /\@([^\[]+)(?<=\@.+)\[(\d+)\]/
return textList
.filter((item) => regex.test(item))
.map((item) => {
const [_, name, id] = item.match(regex)
return {
name,
id
}
})
}
// 准备数据
const textList = [
'@[]', // 不匹配
'@[123]', // 不匹配
'@asd[133]', // 匹配
'@阿里巴巴(杭州)(西湖)[546789][12113][12113][12113][12113][12113][12113]', // 匹配
'@阿里巴巴(杭州)(西湖)[12113]', // 匹配
'@阿里巴巴[444]' // 匹配
]
// 处理
const formatTextList = getFormatTextList(textList)
// 打印结果
console.log(formatTextList)
方法二
在解决问题之前先了解一下贪婪匹配模式和惰性匹配模式。
正则表达式默认采用贪婪匹配模式,在该模式下意味着会匹配尽可能长的子串。我们可以使用
?
将贪婪匹配模式转化为惰性匹配模式。贪婪匹配模式
"/(.*at)/" => The fat cat sat on the mat.
贪婪匹配模式
"/(.*?at)/" => The fat cat sat on the mat.
基于惰性匹配模式,我们用代码来实现一下
// 确定处理函数
const getFormatTextList = (textList) => {
const regex = /\@(.+?)\[(\d+)\]/
return textList
.filter((item) => regex.test(item))
.map((item) => {
const [_, name, id] = item.match(regex)
return {
name,
id
}
})
}
// 准备数据
const textList = [
'@[]', // 不匹配
'@[123]', // 不匹配
'@asd[133]', // 匹配
'@阿里巴巴(杭州)(西湖)[546789][12113][12113][12113][12113][12113][12113]', // 匹配
'@阿里巴巴(杭州)(西湖)[12113]', // 匹配
'@阿里巴巴[444]' // 匹配
]
// 处理
const formatTextList = getFormatTextList(textList)
// 打印结果
console.log(formatTextList)