xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript regular expression in Actions All In One

JavaScript regular expression in Actions All In One

JavaScript 正则表达式实战

demos

在字符串中匹配多组数据

const str = 'lines[0][config][options][343]';
const reg = /\[([0-9]+|[a-z]+|[A-Z]+)\]/g;
const groups = [];

str.replaceAll(reg, group => {
  let value = group.replace(`[`, ``).replace(`]`, ``)
  groups.push(value)
  return ''
});

console.log(`groups =`, groups);
// ['0', 'config', 'options', '343']

// one more thing ✅
const arr = groups.map(item => isNaN(item) ? item : parseInt(item))
console.log(`arr =`, arr);
// [0, 'config', 'options', 343]

image

https://stackoverflow.com/a/76953550/5934465



node.js crawler

const str = "{\"audioMedia\":{\"id\":11917,\"channel\":1,\"mediaType\":0,\"fileId\":\"656ab4e8b42948aa826b4f24791a9b47\",\"fileUrl\":\"https://vod.lagou.com/656ab4e8b42948aa826b4f24791a9b47/838ba0435593c8744dabab77e1d1f160-hq-encrypt-stream.m3u8\",\"duration\":\"19:00\",\"fileSize\":49.55,\"durationNum\":1140},\"videoMedia\":{\"id\":11919,\"channel\":1,\"mediaType\":1,\"fileId\":\"2539bb7e20b44bb79d0ff59b2d475cfb\",\"fileUrl\":null,\"duration\":\"19:00\",\"fileSize\":77.8,\"durationNum\":1140},\"_playInfo\":{\"playURL\":\"https://edu-vod.lagou.com/sv/2daa3bb9-1765150ee6e/2daa3bb9-1765150ee6e.mp4\",\"coverImgURL\":\"https://vod.lagou.com/image/cover/04F29FA68D6D418BA3FB0EA7EEE9558D-6-2.png\"}}"

// ✅
// const reg = /sv\/(.*)\.mp4/ig
// ✅
const reg = /https\:\/\/edu-vod\.lagou\.com\/sv\/(.*)\.mp4/ig
// const reg = /playURL(.*)\.mp4/ig
// 错误的开头 ^ 匹配 ❌
// const reg = /^sv\/(.*)\.mp4/ig
// const reg = /^sv\/(.+\-.+\/.+\-.+)\.mp4/ig
// const reg = /^playURL(\s*\S\s*)*coverImgURL/ig;
// const reg = /^playURL(\s*\S\s*)*coverImgURL$/ig;
// matchAll, groups
// "https://edu-vod.lagou.com/sv/2daa3bb9-1765150ee6e/2daa3bb9-1765150ee6e.mp4"
const groups = [];
str.replaceAll(reg, group => {
  console.log(`❌ group =`, group)
  groups.push(group)
  // groups.push(group.replace(`playURL":"`, ``))
  return ''
});
console.log(`✅ groups`, groups);


image

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/76952844/replace-words-in-string-with-values-of-string-array

https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-08-22 21:11  xgqfrms  阅读(6)  评论(3编辑  收藏  举报