我想使用正则表达式来匹配元标记
<meta name="twitter:title" content="My Favorite Girlfriend"/>
。
但经过多次尝试,还是没能达到这个目标。
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="My Favorite Girlfriend"/>
<meta name="twitter:site" content="@Hulu"/>
</head>
</html>
`;
// regex groups
const result = [];
// html.match(/(^<meta name="twitter:url" content="[.]+"\/>$)/ig, (group) => {
// html.match(/(^<meta name="twitter:url" content="[\w+\s*]+"\/>$)/ig, (group) => {
// html.matchAll(/(^<meta name="twitter:url" content="([\w+\s?]+)"\/>$)/ig, (group) => {
html.matchAll(/(^<meta name="twitter:url" content="[\w+\s?]+"\/>$)/ig, (group) => {
result.push(group);
});
console.log(`result`, result);
我的代码有什么问题?
通过正则表达式工具检查,似乎没问题。
问题似乎出在正则表达式中。您可以尝试以下方法:
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="My Favorite Girlfriend"/>
<meta name="twitter:site" content="@Hulu"/>
</head>
</html>
`;
const result = [];
const regex = /<meta name="twitter:title" content="([^"]+)"\/>/ig;
let match;
while ((match = regex.exec(html)) !== null) {
result.push(match[0]);
}
console.log(`result`, result);
地点:
<meta name="twitter:title"
:匹配所需元素的开始标签。
content="([^"]+)"
:捕获双引号内的内容属性值。
"\/>
:匹配标签的结束。