使用Javascript和regex在括号和空格之间提取文本

时间:2018-06-14 17:27:03

标签: javascript regex

我正在使用Javascript来解析以下用户代理字符串:

"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"

我想在第一个括号和空格之间提取“Windows”一词。如何在Javascript中使用正则表达式来执行此操作?

2 个答案:

答案 0 :(得分:0)

如果第一个括号后的第一个单词只有一个,则可以使用此正则表达式:/\((\w+)/g

var string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0";

console.log(/\((\w+)/g.exec(string)[1] || 0)

答案 1 :(得分:0)

您可以使用String.match()



// Your input string
const string = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0';

// Find string
const match = string.match(/\((.+?)\s/);

// If string was found
if (match !== null) {
  // Get the result
  // match[0] is this whole matched string
  // match[1] is just the matched group
  const result = match[1];
  
  // So something with the result
  console.log(result);
}