简体   繁体   中英

Javascript - How to extract text with regex

I am new to Regexes. Now I need to write one to suit my needs. I have this string:

1 [00:00:12.00 - 00:01:20.00] Hello there - I've come to help you.

I would somehow need to bring it to this form:

const extracted = [
"1",
"[00:00:12.00 - 00:01:20.00]",
"Hello there - I've come to help you."
]

I have tried with this approach:

const testSubject = "1 [00:00:12.00 - 00:01:20.00] Hello there - I've come to help you."
let result = testSubject.match(/\$[^\$]++\$/)

But I am getting this error:

Invalid regular expression: /$[^$]++$/: Nothing to repeat

I have used this place to get the pattern: http://regex.inginf.units.it/

As already pointed out by anubhava, possessive quantifiers ++ are not supported in Javascript. You can see the error message in this demo when selecting Javascript at the left panel.

There is no $ in the string, but if you want to use a negated character class not matching the brackets, you might use a negated character class with a capture group and use split.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM