Regex将CSS选择器转换为块



我想用这个字符串创建一个数组:

// string
'a b[text="Fly to San Fran",text2="More"] c foo[text=Fly to San Fran,text2=More] bar d'
// resulting array:
[
'a',
'b[t="Fly to San Fran",text2=More]',
'c',
'foo[t=Fly to San Fran,text2=More]',
'bar',
'd'
]

如何将一个正则表达式看起来像分割字符串或这是错误的方法?

到目前为止,我尝试了以下操作,结果产生了太多的空值。
/([a-zA-Z]*[[a-z]*])|([w]*)/g
=>
[
'a',
null,
'b[t="Fly to San Fran",text2=More]',
null,
'c',
null
'foo',
null,
[t=Fly to San Fran,text2=More]',
null,
'bar',
null,
'd'
]

[[a-z]*]只匹配[中的字母…]。但有"=,和空格。这里最好使用否定[[^][]*]。这将匹配里面既不是[也不是]的任何字符。

const s = `a b[text="Fly to San Fran",text2="More"] ` +
`c foo[text=Fly to San Fran,text2=More] bar d`;
let res = s.match(/[a-zA-Z]*[[^][]*]|w+/g);
res.forEach(element => console.log(element));

在这种情况下使用正则表达式会非常繁琐。

我建议使用CSS选择器解析库。

在下面的示例中,我们可以使用parsel库对选择器进行标记,然后在标记上使用reduce来组合相邻的标记。

const str = `a b[text="Fly to San Fran",text2="More"] c foo[text=Fly to San Fran,text2=More] bar d`
const tokens = parsel.tokenize(str).map(e => e.content)
const res = tokens.slice(1).reduce((acc, curr) => {
const prev = acc[acc.length - 1]
return curr == " " || prev == " " ? acc.push(curr) : acc[acc.length - 1] += curr, acc
}, [tokens[0]]).filter(e => e != " ")
console.log(res)
<script src="https://projects.verou.me/parsel/dist/nomodule/parsel.js"></script>

最新更新