首页 > 解决方案 > 从复杂字符串中提取文本

问题描述

我的字符串包含

str = "Its a test string @[test_u](89) and @[test_v](91), lets try it."

我正在提取

usernames = str.match(/([^"@\[])[^@\[]+?(?=\]\([1-9]+[0-9]*\))+/g); // ["test_u","test_v"]

我需要以类似的方式提取 id 并且需要["89", "91"]

我有不完整的正则表达式ids = str.match(/([^"(])[^@\(]+?(?=\))+/g);

请建议用于提取 id 的正则表达式。

谢谢

标签: javascriptregex

解决方案


您可以使用捕获组来提取它们:

var rx = /@\[([^\][]+)]\((\d+)\)/g;
var s = "Its a test string @[test_u](89) and @[test_v](91), lets try it."
var keys=[],ids=[], m;
while (m = rx.exec(s)) {
  keys.push(m[1]);
  ids.push(m[2]);
}
console.log(keys);
console.log(ids)

请参阅正则表达式演示。它匹配:

  • @\[- 一个@[字符序列
  • ([^\][]+)]- 第 1 组:除和之外的任何一个或多个字符[
  • ]\(- 一个](子串
  • (\d+)- 第 2 组:一位或多位数字
  • \)- 一个)字符。

推荐阅读