[英]regex find all the strings preceded by = and ending in &
I need to find in a large body of text all the strings that are between = and & symbols. 我需要在大量的文本中找到=和&符号之间的所有字符串。 I don't want the result strings to contain = and &, only whats between them.
我不希望结果字符串包含=和&,只是它们之间是什么。
If your regex engine supports lookbehinds/lookaheads: 如果你的正则表达式引擎支持lookbehinds / lookaheads:
(?<==).*?(?=&)
Otherwise use this: 否则使用这个:
=(.*?)&
and catch capture group 1. 捕获捕获组1。
If your regex engine does not support non-greedy matching replace the .*?
如果您的正则表达式引擎不支持非贪婪匹配,请替换
.*?
with [^&]*
. 用
[^&]*
。
But as zzzzBov mentioned in a comment, if you're parsing GET
URL prefixes there are usually better native methods for parsing GET
arguments. 但正如zzzzBov在评论中提到的,如果你正在解析
GET
URL前缀,通常有更好的本地方法来解析GET
参数。
In PHP for example there would be: 例如,在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
?>
(As found on php.net .) (在php.net上找到。)
Edit: Appears you're using Javascript. 编辑:显示您正在使用Javascript。
Javascript solution for parsing query string into object: 用于将查询字符串解析为对象的Javascript解决方案:
var queryString = {};
anchor.href.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
Source: http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/ 资料来源: http : //stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
Assuming your regex engine supports lookaheads. 假设您的正则表达式引擎支持前瞻。
/(?<==).*?(?=&)/
Edit : 编辑:
Javascript doesn't support lookbehind so : 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);
}
this is what you should use. 这是你应该使用的。
Explanation : 说明:
"
= # 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
)
"
/=([^&]*)&/
您当然需要调整语法以及如何处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.