问题 正则表达式找到所有以=开头的字符串并以&结尾


我需要在大量文本中找到=和&符号之间的所有字符串。我不希望结果字符串包含=和&,只是它们之间是什么。


13157
2017-11-15 18:39


起源

如果你正在解析查询字符串,那么就有更好的方法。无论如何应该用什么语言实现正则表达式? - zzzzBov
我在jquery中这样做,如果这不起作用我将在shell中使用它与grep - anon
你在做什么 JavaScript 然后。 jQuery是一个库,而JavaScript是一种语言。这就像问你说的是什么语言,你回答“国会图书馆”。 - zzzzBov
如果您正在解析您可以看到的查询字符串 stackoverflow.com/questions/2090551/... 要么 我对相关问题的回答 - zzzzBov


答案:


如果你的正则表达式引擎支持lookbehinds / lookaheads:

(?<==).*?(?=&)

否则使用这个:

=(.*?)&

并捕获捕获组1。

如果你的正则表达式引擎不支持非贪婪匹配替换 .*? 同 [^&]*


但正如zzzzBov在评论中提到的,如果你正在解析 GET URL前缀通常有更好的本机解析方法 GET 参数。

例如,在PHP中会有:

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>

(发现于 php.net。)

编辑: 看来你正在使用Javascript。

用于将查询字符串解析为对象的Javascript解决方案:

var queryString = {};
anchor.href.replace(
    new RegExp("([^?=&]+)(=([^&]*))?", "g"),
    function($0, $1, $2, $3) { queryString[$1] = $3; }
);

资源: http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/


13
2017-11-15 18:41





/=([^&]*)&/

您当然需要调整语法以及如何处理它。


0
2017-11-15 18:45



虽然这是正确的,但通常的写作方式是。*?并使用惰性量词。 - FailedDev


假设您的正则表达式引擎支持前瞻。

/(?<==).*?(?=&)/

编辑:

Javascript不支持lookbehind所以:

var myregexp = /=(.*?)(?=&)/g;
var match = myregexp.exec(subject);
while (match != null) {
    for (var i = 0; i < match.length; i++) {
        // matched text: match[i]
    }
    match = myregexp.exec(subject);
}

这是你应该使用的。

说明:

"
=       # Match the character “=” literally
(       # Match the regular expression below and capture its match into backreference number 1
   .       # Match any single character that is not a line break character
      *?      # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
(?=     # Assert that the regex below can be matched, starting at this position (positive lookahead)
   &       # Match the character “&” literally
)
"

0
2017-11-15 18:42