正则表达式在括号之间的关键字后匹配字符串

时间:2019-05-02 05:42:55

标签: javascript regex source-engine

我需要在双引号之间的关键字后匹配值 例如:

zoom_sensitivity "2"
sensitivity "99"
m_rawinput "0"
m_righthand "0"

也具有不同的间距:

sensitivity"99"m_rawinput"0"zoom_sensitivity"2"m_righthand"0"

另一个例子:

sensitivity"99" m_rawinput "0"
m_righthand "0"
zoom_sensitivity"2"

在两种情况下,我想通过敏感性关键字或选择一个来获得99

我尝试过的是: [\n\r]*["|\n\r\s]sensitivity\s*"([^\n\r\s]*)"

,但如果关键字在第一行或任何空格/双引号之前,并且与内联代码匹配,则匹配项不仅仅与 99 值匹配。 我相信Source Engine从其.cfg文件中解析出的内容类似,也许还有更好的方法。

2 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式从组1中捕获数字,

\bsensitivity\s*"(\d+)"

要选择仅在99之后的sensitivity作为整个单词,需要在单词周围使用单词边界\b,例如\bsensitivity\b和{{ 1}}允许匹配单词之间的可选空格,然后\s*匹配双引号,然后"匹配一个或多个数字并捕获到group1中,最后(\d+)匹配结束的双引号。

Regex Demo

答案 1 :(得分:1)

您可以简单地这样使用:

()=>

哪个输出

(\w+)\s?"(\d+)"

为此:

zoom_sensitivity "2"    zoom_sensitivity    2
sensitivity "99"        sensitivity         99
m_rawinput "0"          m_rawinput          0
m_righthand "0"         m_righthand         0
sensitivity"99"         sensitivity         99
m_rawinput"0"           m_rawinput          0
zoom_sensitivity"2"     zoom_sensitivity    2
m_righthand"0"          m_righthand         0
sensitivity"99"         sensitivity         99
m_rawinput "0"          m_rawinput          0
m_righthand "0"         m_righthand         0
zoom_sensitivity"2"     zoom_sensitivity    2

您可以将其放入一个对象中,然后再查询该对象:

zoom_sensitivity "2"
sensitivity "99"
m_rawinput "0"
m_righthand "0"
also with different spacing:

sensitivity"99"m_rawinput"0"zoom_sensitivity"2"m_righthand"0"
another example:

sensitivity"99" m_rawinput "0"
m_righthand "0"
zoom_sensitivity"2"
var parse = function(content) {
  var myregexp = /(\w+)\s*"(\d+)"/mg;
  var match = myregexp.exec(content);
  while (match != null) {
    // matched text: match[0]
    // match start: match.index
    // capturing group n: match[n]
    console.log(match[1] + " => " + match[2]);
    // re-run the regex for the next item
    match = myregexp.exec(content);
  }
}

parse(document.getElementById("example1").innerHTML);
console.log("-----------");
parse(document.getElementById("example2").innerHTML);
console.log("-----------");
parse(document.getElementById("example3").innerHTML);