我需要在大量文本中找到=和&符号之间的所有字符串。我不希望结果字符串包含=和&,只是它们之间是什么。
我需要在大量文本中找到=和&符号之间的所有字符串。我不希望结果字符串包含=和&,只是它们之间是什么。
如果你的正则表达式引擎支持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/
/=([^&]*)&/
您当然需要调整语法以及如何处理它。
假设您的正则表达式引擎支持前瞻。
/(?<==).*?(?=&)/
编辑:
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
)
"