-1

Just like title says , code behind like

var re = /^\S(if\([\s\S]*?\)\s*?\{)([\s\S]*?)(\})(?:\s*?(else\s*?\{)([\s\S]*?)(\}))?/g;
var str = "@if(bool) { @{code} <div>@(var)</div>} else {  @while(condition){ @{ } <div>@(var)</div>} <div>str</div> }"

//first time execute
re.test(str);    //true

//second time execute
re.test(str);    //false

//third time execute
re.test(str);   //true

The even times I execute result is true , the odd times I execute is false .

The Situation Is I am building a front-end template engine , the razor style , I want it can parse code template like this

@if(some condition)
{
    <div>@(some variable or sentence code)</div>
    @for(var i = 0; i < 10 ; i ++)
    {
        <div>@(i)</div>
    }
}
else
{
    <div>bla bla ...</div>
}

So I need to use Regex to fetch the template part , but I account this problem now , looks weird ... any help or guide ,thanks ...

magicdawn
  • 27
  • 3
  • 1
    See http://stackoverflow.com/questions/2851308/why-does-my-javascript-regex-test-give-alternating-results, or http://stackoverflow.com/questions/2630418/javascript-regex-returning-true-then-false-then-true-etc or http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results or http://stackoverflow.com/questions/12367471/strange-behavior-of-javascript-regexp-same-regular-expressions-produce-different. Next time, please search before asking a question. – Matt Apr 16 '14 at 13:45
  • That's how it's supposed to work. Consider trying `str.match(re)` instead if you want a "stable" result. – Niet the Dark Absol Apr 16 '14 at 13:45
  • 1
    Global flag fun. Minimal testcase: `var re = /a/g, str = 'a';` and `re.test(str)` twice – Paul S. Apr 16 '14 at 13:47
  • @Matt Thanks ,i don't know it's caused by the global flag before i get answer from you , I searched "javascript regex stable" but no result match . Thanks again . – magicdawn Apr 16 '14 at 14:19

1 Answers1

0

If you want to make your own langage, you could also use a BNF grammar, and then a parser that uses this grammar (or do it manually, it is possible). This is a little more complicated to code, but it will be really more reliable and easy to debug.

From what i see the informal grammar should look like

s->Tags | Instruction | Value
Value->@(id)
Instruction->@id{ S }
Tags-> (HTML grammar here)
id->[0-9a-z]+
Matt
  • 74,352
  • 26
  • 153
  • 180
pdem
  • 3,880
  • 1
  • 24
  • 38
  • BNF never heard. I am just using javascript to parse templateString to htmlString, I can finish it with regex, just hard to debug. I will keep an eye. Thanks. – magicdawn Apr 16 '14 at 14:24
  • 1
    The grammar is the main concept to parse any languages. C, Java, Javascript compiler/interpreter are probably coded using that concept, to go further: http://stackoverflow.com/questions/6641017/what-are-context-free-grammars-and-backus-naur-form – pdem Apr 16 '14 at 14:40