我需要在一大段文本中找到所有位于等号和&符号之间的字符串。我不想要结果字符串包含等号和&,只需要它们之间的内容。
我需要在一大段文本中找到所有位于等号和&符号之间的字符串。我不想要结果字符串包含等号和&,只需要它们之间的内容。
如果你的正则表达式引擎支持回顾后发/前发:
(?<==).*?(?=&)
否则使用这个:=(.*?)&
并捕获第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不支持向后查找,因此:
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
)
"
/=([^&]*)&/
当然,你需要根据语法和具体情况进行适应。
JavaScript
进行编程。jQuery 是一个库,而 JavaScript 是一种语言。这就像问你在说什么语言,你回答“国会图书馆”。 - zzzzBov