javascript - 从复杂字符串中提取文本
问题描述
我的字符串包含
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 的正则表达式。
谢谢
解决方案
您可以使用捕获组来提取它们:
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 组:一位或多位数字\)
- 一个)
字符。
推荐阅读
- java - IntelliJ IDEA 模块信息警告
- linux - 使用 phc2sys 获得较大的偏移量
- python - 显示在 printf 语句之外的值
- java - 在 java 中为 tesseract OCR 预处理图像(局部阈值)?
- ruby - RubyMine 调试 gem 版本与公共 gem 版本不同
- python - Gensim Word2Vec 的内部工作原理
- ios - 你如何为 iOS DatePicker Xamarin 制作自定义渲染器
- amazon-web-services - 如何正确使用安全组内的 VpcId 属性?
- javascript - 如何在Angular的嵌套地图函数中收集每个用户的所有响应?
- python - 使用 PostGIS 查找最近点