Home  >  Q&A  >  body text

Javascript Regular Expressions: How to keep only matching groups for an arbitrary regular expression?

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粉574695215P粉574695215276 days ago364

reply all(1)I'll reply

  • P粉071626364

    P粉0716263642024-01-17 15:46:08

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

    reply
    0
  • Cancelreply