0

I want to divide a string by spaces, but only if the spaces are not within square brackets. For example:

"What a [nice sunny] day"

After dividing, it should look like this:

[What, a, [nice sunny], day]

I tried to find the solution on my own, but I'm afraid I'm not enough familiar with RegExp in javascript.

undefined
  • 27
  • 1
  • 4
  • `"What a [nice sunny] day".match(/(^|\s)(\[[^\]]+\]|\S+)/g)`. – Rob W May 06 '12 at 10:53
  • `"What a [nice sunny] day".match(/\[[^\]]*\]|[\S]+/g)` – Dagg Nabbit May 06 '12 at 10:53
  • Borrowing from @GGG, `var yourstring = yourstring.match(/(\[[^\]]*\]|[\S]+)/ig).join(', ');` – Nadh May 06 '12 at 10:56
  • Thank you all for quick responses! All of them worked very well, but GGG's version did exactly what I wanted. How do I accept it as a correct answer? – undefined May 06 '12 at 11:17
  • Leave a message in the format @GGG to notify him that there's a comment, and leave a message asking him to post his comment as an answer. – David Thomas May 06 '12 at 11:26
  • @user1377881 mark Rob W's, he beat me by a few seconds on the first comment :) – Dagg Nabbit May 06 '12 at 11:32
  • @GGG `[\S]+` is equivalent to `\S+`. Any reason that you used `[\S]` instead of `\S`? – Rob W May 06 '12 at 11:36
  • @RobW nope, those are leftovers, I had some other stuff in there when I was playing with it in the console. I tried to edit it out but the comments wouldn't let me. =p – Dagg Nabbit May 06 '12 at 11:40

1 Answers1

1

When the space has to be included, the following RegEx is needed:

"What a [nice sunny] day".match(/(^|\s)(\[[^\]]+\]|\S+)/g)
// Outputs: ["What"," a"," [nice sunny]"," day"]

In the comments, it became obvious that the spaces have to be removed:

"What a [nice sunny] day".match(/\[[^\]]+\]|\S+/g)
// Outputs: ["What","a","[nice sunny]","day"]
Rob W
  • 341,306
  • 83
  • 791
  • 678