4

Let's pretend we have the following import statements (not language-specific):

import "./test"

import "./test" as Test

import { Test } from "./test"

import { Person as Individual } from "./test"

I'm trying to write a regular expression to retrieve the following groups, in bold:

import "./test"

import "./test" as Test

import { Test } from "./test"

import { Person as Individual, Test, Bag as Backpack } from "./test"

I tried writing the following regex:

/^(import)(?:.+?)(\s+from\s+|\s+as\s+)*(?:.+?)$/gm

https://regex101.com/r/4sO59R/1

But it didn't work how I was expecting... I can only get the import... How should I properly write it?

  • Please explain what you need to do with all these captures: replace, remove, extract, wrap? Are they standalone strings or lines in a multiline text? It sounds as if you need a whole dedicated language parser. Your regex would not work since your group is optional and the last `.+?` grabs the whole text to the end of the string earlier than this group can match its pattern in full. Anyway, repeated captures are not supported even if you fix it. – Wiktor Stribiżew Oct 05 '18 at 08:45

2 Answers2

2

Although an ideal regex for capturing your data seems quite hard, the closest I could come up is this for your given text,

^(import)(?:.*?(as))?(?:.*?(as))?(?:.*?(from))*.*$

Play here https://regex101.com/r/7aIudD/1

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
1

This might work also and be easier to understand.

\b((^import)|(as)|(from))\b

Try it here:

https://regex101.com/r/7aIudD/2

EDIT: I should add I just noticed that you are using Javascript, so repeating captures may not be supported. That means you may have to resort to manual means to search your strings ( not hard) or split up string somehow and do multiple searches. I would be going for the manual search if the problem is as simple as you described.

bcperth
  • 2,191
  • 1
  • 10
  • 16
  • Your regex matches unintended input text as per OP such as 'as' or 'from as' or 'from' or 'as from' etc. which is unintended as per OP. OP wants them to match in certain order and it must always begin with import. – Pushpesh Kumar Rajwanshi Oct 05 '18 at 19:39
  • Yes indeed, and thanks - any well done for your reply which I upvoted yesterday! My little effort passed his test data and I did not look further. In any case I think Wiktor Stribiżew's comment is relevant that neither may work with Javascript anyhow, which is why I added the edit. – bcperth Oct 05 '18 at 22:40
  • Indeed, I too liked your simple and neat approach for the regex you came up with that at least matched well. And thank you for the upvote. – Pushpesh Kumar Rajwanshi Oct 06 '18 at 07:51