Tomás Juárez
Tomás Juárez

Reputation: 1514

Get the matches from specific groups

I want to validate a String and, after that, get all the matches from some groups.

RegEx:

/^<[A-Za-z0-9]>::=(<[A-Za-z0-9]>)+(\|(<[A-Za-z0-9]>)+)+$/

So, if I get something like <A>::=<B><A>|<Y><A>|<Z> is valid, but if I get something like <A>::=<B>| is false.

There's no problem with the validation, the problem is that I want to take the text inside < and > because I need it later.

So, if I get <exparit>::=<number>|<number><exparit>, then I want to get ["exparit", "number", "number", "exparit"]

My code looks like

Rules = {
  "BNF" : /^<[A-Za-z0-9]>::=(<[A-Za-z0-9]>)+(\|(<[A-Za-z0-9]>)+)+$/
};

var checkBNF = function ( bnf ) {
  if ( Rules.BNF.test( bnf ) ) {
    console.log('ok');
    //How to get the text inside < and > ??
  }
  else {
    console.log('no');
  }
};

I really appreciate any kind of help, such a book, link, example or the resolution of this problem.

Thanks!

Upvotes: 1

Views: 74

Answers (2)

Chris Rymer
Chris Rymer

Reputation: 713

What I did was slightly different as I wasn't sure that you would only ever have [a-zA-Z0-9] within the <>

Rules = {
  "BNF" : /^<[A-Za-z0-9]>::=(<[A-Za-z0-9]>)+(\|(<[A-Za-z0-9]>)+)+$/
};

var checkBNF = function ( bnf ) {
  if ( Rules.BNF.test( bnf ) ) {
    console.log('ok');

    //How to get the text inside < and > ??
    var patt = /\<(.*?)\>/g;
    var strArray = bnf.match(patt);
    for (i=0;i<strArray.length;i++) {
        strArray[i] = strArray[i].replace('<','').replace('>','');
    }
    return strArray;
  }
  else {
    console.log('no');
  }
};

var test = "<A>::=<B><A>|<Y><A>|<Z>";
var result = checkBNF(test);
console.log(result)

http://jsfiddle.net/UmT3P/

Upvotes: 1

Theox
Theox

Reputation: 1363

If I can help you a bit, here's something to stat with :

http://jsfiddle.net/URLhb/1/

var test = "<A>::=<B><A>|<Y><A>|<Z>";

var patt0 = /<([a-zA-Z]*)>/g; //Old and bad version
var patt1 = /[a-zA-Z]+/g;

var testRE = test.match(patt1);



alert(testRE[0]);
alert(testRE[1]);
alert(testRE[2]);
alert(testRE[3]);
alert(testRE[4]);
alert(testRE[5]);

This code will capture the text inside the < >, but also the < and > symbols with it. I'm trying to fix this, I'll update if I get a better result.

EDIT : Found the issue : I was using a * instead of a + ! It works perfectly now !

Upvotes: 2

Related Questions