Regex to find if there is only one block of code

前端 未结 4 1500
滥情空心
滥情空心 2021-01-07 12:51

My input is a string, I want to validate that there is only one first-level block of code.

Examples :

{ abc }              TRUE
{ a { bc }         


        
4条回答
  •  走了就别回头了
    2021-01-07 13:38

    In JavaScript what you need to do is strip out all the nested blocks until no nested blocks are left and then check whether there are still multiple blocks:

    var r = input.replace(/(['"])(?:(?!\1|\\).|\\.)*\1|\/(?![*/])(?:[^\\/]|\\.)+\/[igm]*|\/\/[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*\*\//gi, '');
    
    if (r.split('{').length != r.split('}').length || r.indexOf('}') < r.indexOf('{')) {
        // ERROR
        continue;
    }
    
    while (r.match(/\{[^}]*\{[^{}]*\}/))
        r = r.replace(/(\{[^}]*)\{[^{}]*\}/g, '$1');
    if (r.match(/\}.*\{/)
        // FALSE
    else
        // TRUE
    

    Working JSFiddle

    Be sure to make the regex in the while and the regex in the replace match the same otherwise this might result in infinite loops.

    Updated to address ERROR cases and remove anything in comments, strings and regex-literals first after Unihedron asked.

提交回复
热议问题