split a string with two types of groups, ignoring characters in one

-5

Example inputs and outputs:

Input 1 "request.partner"

Output 1 [request, partner]

Input 2 "request.partner(invite: https://discord.gg, desc: poop).info(stuff)"

Output 2 [request, partner, (invite: https://discord.gg, desc: poop), info, (stuff)]

Input 3 "request(poop).partner(invite: https://discord.gg, desc: poop).info(stuff).again(poop)"

Output 3 [request, (poop), partner, (invite: https://discord.gg, desc: poop), info, (stuff), again, (poop)]

So as you can see, I need an array generated from each string, possibly using the .split method. I would need to ignore the periods inside the parentheses and also have the code be able to take in an infinite amount of period and parentheses splits.

For periods:

  1. Split the string between them. Say using: str.split('.');
  2. Do not split the string when they are inside of parentheses at any place

For parentheses:

  1. They must always be split before they are shown and must be collected with the string in the array.
  2. They must be nested so "partner).reg" would still be [partner), reg]. They would always need to be a set, and facing inwards (()).

Possible ways to solve this would include:

  1. Using a RegEx in the split statement to divide it into an array (shortest)
  2. Using a combination of a RegEx in a .split and other JS methods
  3. Using a loop that picks off matches and inserts them into an array

Here is an answer that works but I would like it to be shorter and a bit less complicated:

let str = "request.partner(invite: https://discord.gg, desc: poop).info(stuff)";
let arr = [],
    reg = /\.(\w+)(\([^\)]+\))/g,
    f = str.split(".").shift(),
    it;
arr.push(f)
while(it = reg.exec(str.slice(f.length)))
  arr = arr.concat(it.slice(1));

I'm looking for the shortest possible JS answer!

Seth Deegan

Posted 2018-06-07T02:44:36.100

Reputation: 1

Question was closed 2018-06-07T04:32:17.500

Comments are not for extended discussion; this conversation has been moved to chat.

– Mego – 2018-06-10T20:22:54.413

Answers

1

Since it looks like you want a line of JS code:

let arr = "request.partner(invite: https://discord.gg, desc: poop).info(stuff)".match(/(\w+)|(\([^\)]+\))/g)

might be what you want...

Stack Overflow may be better for these questions later on...

EDIT

OP was unclear because there were no quotation marks to differentiate between whether something was in a string or not, following OP's rules for parentheses:

let arr = "request.partner(invite: https://discord.gg, desc: poop).info(stuff)".match(/(\([^\,\)]+\)*)|(\w+\: \w+\)*)|(\w+)/g)

may be what OP actually wants.

This produces an array:

[
  "request",
  "partner",
  "(invite: https://discord.gg",
  "desc: poop)",
  "info",
  "(stuff)"
]

I'm not very good at regexp so this could it could possibly be shortened much more.

Brian Lu GeekyStudios

Posted 2018-06-07T02:44:36.100

Reputation: 11