Javascript Regular Expressions: How to keep only matching groups for an arbitrary regular expression?
P粉574695215
P粉574695215 2024-01-16 22:01:08
0
1
434

Is there a way in the JS regex API to rewrite the input so that only matching groups are kept (in order), but it works with arbitrary regexes (including regexes without capturing groups)?

For example for the regular expression /abc([D-F] )gh([I-K] )/ and input abcFEEDghKIKI, I want to output "FEEDKIKI" , because these are the captured parts.

However, the input regular expression can also be /([a-zA-Z] )/, which will just return the original text for the same input.

If the regular expression is /([0-9] )/, an empty string will be returned.

The regex will be generated by the tool, but there are many regexes and I don't want special case code for different numbers of capturing groups.

Ideally I would also be able to access the length of the match in the input somehow.

I'm assuming there is some way to accomplish this via a callback passed to replace() (or similar), but it's not clear how/if I can get the index of the capturing group (or in JS whether it is necessary).

Essentially, I'm trying to replicate what you can do via the MatchResult API in Java, where groups can be iterated over and the start/end index of the capturing group can be found. < /p>

Thanks in advance!

P粉574695215
P粉574695215

reply all(1)
P粉071626364

Discover: How to access JavaScript regular expressions? It looks like (at least initially) using exec() will do what I want.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template