首页 > 解决方案 > 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/

标签: javascriptnode.jsregex

解决方案


正如 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))


推荐阅读