0

I never was a regex expert, so I need some help with the following.

I have the following string: '<param1>(/<param2>(/<param3>(/<param4>)))'. This is a kind of url structure. I want to extract: 'param1', 'param2', 'param3', 'param4' and to check if they are optional. A param is optional if it is in parenthesis (param2, param3 and param4 in this case).

Thanks in advance.

2
  • 2
    This seems like it would be better done as a parser, not using a regex. You want to loop through each character, pushing a level onto a "stack" every time you hit a ( and popping if you hit a ). You have an optional parameter if the stack is not empty. Commented Feb 20, 2012 at 8:50
  • Yes, you are right. It is better to write a parser for this. Thanks! Commented Feb 20, 2012 at 9:15

3 Answers 3

1

This may help you:

var str = '<param1>(/<param2>(/<param3>(/<param4>)))';
var optionnals = str.match(/\/<\w+>/g).map(function(s) { return s.replace(/\/<(\w+)>/, "$1"); });

But it might be difficult to have deep/recursive matching.

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

Comments

1

This works:

//var str = '<param1>';
//var str = '<param1>(/<param2>)';
//var str = '<param1>(/<param2>(/<param3>))';
var str = '<param1>(/<param2>(/<param3>(/<param4>)))';

var result = str.match(/^<(.*?)>(?:\(\/<(.*?)>(?:\(\/<(.*?)>(?:\(\/<(.*?)>\))?\))?\))?/);

console.log(result[1]); //param1
console.log(result[2]); //param2
console.log(result[3]); //param3
console.log(result[4]); //param4

Comments

-1

May be without regex?

var str = 'param1/param2/param3/param4';
var res = str.split('/');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.