使用正则表达式获取未括在括号中的分号

时间:2016-02-16 06:14:32

标签: javascript regex

这是我的文本,如何使用RegExp获取未用括号括起来的分号。

Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/538.2 (KHTML, like Gecko) Large Screen Safari/538.2 LG Browser/7.00.00(LGE; 65UF8500-UB; 04.00.45; 1; DTV_W15U); webOS.TV-2015; LG NetCast.TV-2013 Compatible (LGE, 65UF8500-UB, wireless)

2 个答案:

答案 0 :(得分:1)

您需要用空字符串替换括号。您的文本中有多个括号,因此最好使用非贪婪的正则表达式,如\(.+?\)

var text = "Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/538.2 (KHTML, like Gecko) Large Screen Safari/538.2 LG Browser/7.00.00(LGE; 65UF8500-UB; 04.00.45; 1; DTV_W15U); webOS.TV-2015; LG NetCast.TV-2013 Compatible (LGE, 65UF8500-UB, wireless)";
var output = text.replace(/\(.+?\)/g, "");
console.log(output);

非贪婪的正则表达式选择可能的最小块,而不是从第一个到最后一个括号中进行选择。

当你的文字包含彼此的括号时,你可能会遇到麻烦,但我会尝试编辑它。

答案 1 :(得分:0)

试试这个

var str = 'Mozilla/5.0 (Web0S; Linux/SmartTV) AppleWebKit/538.2 (KHTML, like Gecko) Large Screen Safari/538.2 LG Browser/7.00.00(LGE; 65UF8500-UB; 04.00.45; 1; DTV_W15U); webOS.TV-2015; LG NetCast.TV-2013 Compatible (LGE, 65UF8500-UB, wireless)';
var regex = /\(.*?\)|([^\W_]+[^\s-]*)/g;
var arr = [];
var newstr = '';
var match = regex.exec(str);

while (match != null) {
    if( match[1] != null ) arr.push(match[1]);
    match = regex.exec(str);
}

if (arr.length > 0) {
   for (key in arr) newstr = newstr+ " " + arr[key];
}
console.log(newstr);