0

I am building myself a syntax highlighter for React tutorials. Currently I am trying to capture the variable assignment and de-structured properties when importing.

I am able to capture a single variable assignment like so...

code: import React from 'react';

regex: /(?<=\b(import|export|default)\s)(\w+)/gm

captures: React

However, when trying to capture that inline with de-structured properties it fails and I am running into unforseen issues.

Example

code: import React, { useState, useEffect } from 'react';

captures: React

I Need to capture React, useState, and useEffect but not ,, {, or }.

Regex is not my forte and I am unsure how to ask this question to get a proper answer. Any help would be appreciated.

  • Reminds me of https://stackoverflow.com/a/1732454/5260024 – Jonas Wilms Dec 08 '19 at 17:35
  • In this specific capture, I'm not parsing html, I am simply trying to capture import declarations. Specifically I need to capture everything between the words 'import' and 'from' that are a-z characters and exclude commas, curly brackets and the actual words 'import' and 'from' – Brandon Carr Dec 08 '19 at 17:43
  • 1
    Well then `(?<=\b(import|export|default)(\w|\s|\,|\{|\}|\*)*)(\w+)(?=.*from)` – Jonas Wilms Dec 08 '19 at 17:44
  • Thank you so much, that works like a charm! Can you please post your comment so I can mark it as the accepted answer? – Brandon Carr Dec 08 '19 at 17:50

1 Answers1

0
  (?<=\b(import|export|default)(\w|\s|\,|\{|\}|\*)*)(\w+)(?=.*from)

Line by line:

 (?<=\b /*positive lookbehind*/
   (import|export|default) /* for the statements */
   (\w|\s|\,|\{|\}|\*)* /* and for all kinds of chars inbetween */
 )(\w+) /* the word */
 (?=.*from) /* positive lookahead for "from" */
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151