javascript - Javascript - 如何使用正则表达式提取文本
问题描述
我是正则表达式的新手。现在我需要写一个来满足我的需要。我有这个字符串:
1 [00:00:12.00 - 00:01:20.00] 你好 - 我是来帮你的。
我会不知何故需要把它带到这种形式:
const extracted = [
"1",
"[00:00:12.00 - 00:01:20.00]",
"Hello there - I've come to help you."
]
我尝试过这种方法:
const testSubject = "1 [00:00:12.00 - 00:01:20.00] Hello there - I've come to help you."
let result = testSubject.match(/\$[^\$]++\$/)
但我收到此错误:
无效的正则表达式:/$[^$]++$/:无需重复
我用这个地方来获取模式: http ://regex.inginf.units.it/
解决方案
正如 anubhava 已经指出的那样,++
Javascript 不支持所有格量词。在左侧面板中选择 Javascript 时,您可以在此演示中看到错误消息。
字符串中没有$
,但是如果您想使用与括号不匹配的否定字符类,您可以使用带有捕获组的否定字符类并使用拆分。
const pattern = /\s*(\[[^\][]+])\s*/;
const s = "1 [00:00:12.00 - 00:01:20.00] Hello there - I've come to help you.";
console.log(s.split(pattern))
推荐阅读
- java - 出现错误 :: 此表达式的目标类型必须是函数式接口
- python - 为什么 python 程序没有创建任何像素?
- julia - 在 WSL 上向 Julia 添加包
- amazon-s3 - 在中国托管的 S3 中上传/下载文件时出现 OptionRequestDenied 错误
- google-sheets - 有没有办法执行 VLookup 或类似的函数来返回最后一个值?
- image - Flutter 中的图像尺寸
- google-apps-script - 从另一个具有固定列和可变行的工作表中获取单元格的值
- apache-spark-sql - 使用 PySpark 展平层次结构表
- c - 如何在 C 中初始化结构?
- java - Java XML - 在新元素中添加现有元素