0

I have an html checkbox element with the following name:

type_config[selected_licenses][CC BY-NC-ND 3.0]

I would like to break this name apart as follows and returned as part of an array:

["type_config",  "[selected_licenses]", "[CC BY-NC-ND 3.0]", "[selected_licenses][CC BY-NC-ND 3.0]"]

I thought I could do this by using a regular expression in javascript. Here is the expression that I am using:

matches = /([a-zA-Z0-9_]*)((\[[a-zA-Z0-9_\.\s]*\])+)*/.exec(element_name);

but this is the result I am getting in my matches variable:

["type_config[selected_licenses]", "type_config", "[selected_licenses]", "[selected_licenses]", index: 0, input: "type_config[selected_licenses][CC BY-ND 3.0]"]

I am half way there. What am I doing wrong in my regular expression? I guess I should also ask if it is possible to accomplish what I want with a regex?

Thanks.

3
  • You can use \w instead of [a-zA-Z0-9_]. You can use it even inside [], like [\w\.\s]. Commented Jan 13, 2014 at 23:34
  • Thanks for the tip, I will make that change. However it doesn't resolve my question. Commented Jan 13, 2014 at 23:40
  • In fact, I've readied an answer for that. Check it out! ;) Commented Jan 13, 2014 at 23:41

2 Answers 2

1

The problem with this kind of goal is that there's no simple way to achieve this with regular expression, i.e. a simple match call. In short, even if you put a quantifier after a capturing group, the captured string will always be just one.

You'll have to rely on something more specific, like breaking the string with a repeated use of indexOf, or something like

name.split(/(?=\[)/);

Maybe you want to be sure that name is formally correct.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, too quick to respond on my part :-). So it isn't possible - that is good to know. I will go with what you suggested above.
0

This is a very ugly problem. I don't know how repeatable this is, but I can do it:

Regex

^(\w+)(?<firstbracket>\[(?<secondbracket>[^]]*)\]\[(.*?)\])$

Replacement

["$1", "[$3]", "[$4]", "$2"]


Demo

http://regex101.com/r/eD9mH8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.