请教怎么正则这个

[哈哈]
呵呵[呵呵]

[嘎嘎]
呵呵[哼哼]

怎么只匹配出 哈哈 和 嘎嘎 呢?

主要是想取 [ ] 里的内容

并且是在单独一行上的

阅读 3.3k
4 个回答
var str=`[哈哈]
呵呵[呵呵]

[嘎嘎]
呵呵[哼哼]`;

方法一:

str.match(/^\[([^\[\]]+)\]$/mg).map(function(item,i){
    return item.replace(/[\[\]]/g,'');
});

方法二:

var match=null;
var result=[];
var regex=/^\[([^\[\]]+)\]$/mg;
while((match=regex.exec(str))!=null){
    result.push(match[1]);
}
let reg = /哈哈|嘎嘎/
    reg.test('测试测试测试嘎嘎测试')

替换例子:

let str = '测试哈哈测试嘎嘎测试'
    str.replace(/哈哈|嘎嘎/g, '替换') 
    //测试替换测试替换测试
let str = `[哈哈]
呵呵[呵呵]

[嘎嘎]
呵呵[哼哼]`; 

const regex = /(\[哈哈\])|\[嘎嘎\]/g;
const regex2 = /^\[[^\[\]]+\]$/mg;

const outputMatches = matches => {
    [...matches].forEach( m => {
        console.log(m[0].slice(1,m[0].length-1),'position: ', m.index +1 ); 
    }); 
}

// output: -------------
// 哈哈 position:  1
// 嘎嘎 position:  14
let matches = str.matchAll(regex);
outputMatches(matches); 

// find the row which is wrapped in [], and output whatever in the []: -------------
// 哈哈 position:  1
// 嘎嘎 position:  14
matches = str.matchAll(regex2);
outputMatches(matches); 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题