[哈哈]
呵呵[呵呵]
[嘎嘎]
呵呵[哼哼]
怎么只匹配出 哈哈 和 嘎嘎 呢?
主要是想取 [ ] 里的内容
并且是在单独一行上的
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);
10 回答11.7k 阅读
2 回答3.2k 阅读✓ 已解决
2 回答4.2k 阅读✓ 已解决
4 回答4.6k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
3 回答2.7k 阅读✓ 已解决
4 回答2.1k 阅读✓ 已解决
方法一:
方法二: