js正则匹配字符串中的完整Class类,大花括号内可能嵌套有花括号!

新手上路,请多包涵

匹配的字符串:
var str = 'asfsdf class Bop { public double breadth; public double height; static void get(){ var test = asas; var ssasd = function(){} } static void set(){} } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); Box Box2 = new Box(); double volume = 0.0; // Box1 详述 Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; } }'

要匹配出来的字段是:
class Bop { public double breadth; public double height; static void get(){ var test = asas; var ssasd = function(){} } static void set(){} }

class类名是变量,所以要用new RegExp

这是我写的一部分,但匹配不全:

    var word = 'Bop';        
    var res = new RegExp("class\\s+"+word+"\\s*\\{(\\s+(.+?)\\s+)*\\}","g");
    console.log(res.exec(str))
   

求教各位大神!

阅读 2.4k
1 个回答
✓ 已被采纳新手上路,请多包涵

实现方案已改变:
1.匹配到 class Bop { 即可,然后字符串截取到当前的index至最后
2.遍历截取的字符串,遇到‘{’ 和 ‘}’时赋值给增加变量,当两变量相同时就能截取到想要的结果

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题