我试图提取美国'从以下字符串,但它返回null,任何想法?感谢
console.log('sample sample 1234 (US)'.match(/\(W{2}\)$/))
答案 0 :(得分:1)
W
匹配字母W
。它应该是\w{2}
或更好[A-Z]{2}
。使用(...)
捕获它并访问第一个捕获的值:
console.log('sample sample 1234 (US)'.match(/\(([A-Z]{2})\)$/)[1]);
// Or, with error checking
let m = 'sample sample 1234 (US)'.match(/\(([A-Z]{2})\)$/);
let res = m ? m[1] : "";
console.log(res)
如果您不想访问捕获组的内容,则需要对/\([A-Z]{2}\)$/
正则表达式的结果进行后处理:
let m = 'sample sample 1234 (US)'.match(/\([A-Z]{2}\)$/);
let res = m[0].substring(1, m[0].length-1) || "";
console.log(res);