正则表达式创建

declare module 'api/*' {
export const getPaperInfo: any;
}

这段代码如何使用正则表达式表达,花括号中的值可以为任意值

阅读 2.4k
3 个回答
    //多行匹配 m
    let reg = /{([\w\W]+?)\}/mg
    
    let str = `declare module 'api/*' {
        export const getPaperInfo: any;
    }{2332}`
    
    str.match(/{([\w\W]+?)\}/mg)
    // 结果 ["{↵    export const getPaperInfo: any;↵}", "{2332}"] 

因为js正则好像不能连续行的匹配,所以先去掉换行符,再处理

var str = `declare module 'api/*' {
export const getPaperInfo: any;
}`;
// 改为单行字符串
str = str.replace(/\n/mg,'');
// 正则匹配
var match_array = str.match(/declare module \'api\/\*\' {(.*?)}/);
console.log(match_array[1]);

结果:

"export const getPaperInfo: any;"

单纯一个正则表达式目测无解,或者会超级复杂。因为要界定结尾的}是异常困难的,因为你不知道花括号里面到底有没有}字符,或者花括号里面存在字符串里面有任意多的}字符。

举个例子

declare module 'api/*' {
    if(1){
        while(1){
            try{
                str="}}}}}}}}}}}}}" //如果是任意内容,唯有按语法进行解析才是正道,一个正则想搞定,门都没有~
            }
        }
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题