[英]JavaScript: Using regex to extract characters between other characters
Consider this string,考虑这个字符串,
var string = "sometext/#a=some_text/#b=25/moretext";
What I would like to do is extract the values of "a" and "b" ("some_text" and 25)我想做的是提取“a”和“b”(“some_text”和25)的值
So essentially what I want to do is find "#a="
and grab everything before the following /
, then do the same for b.所以基本上我想要做的是找到
"#a="
并在以下/
之前抓取所有内容,然后对 b 做同样的事情。 How can this be accomplished?如何做到这一点? Additionally, would I use the same expression to change the values in the string?
另外,我会使用相同的表达式来更改字符串中的值吗?
I got a hand doing this with PHP, but now I can't figure it out for JavaScript.我用 PHP 做了这件事,但现在我无法弄清楚 JavaScript。
Here's the PHP version of extraction:这是提取的PHP版本:
$string = "sometext/#a=some_text/#b=25/moretext";
$expr = '@#([a-z]+)=(.+?)/@';
$count = preg_match_all($expr, $string, $matches);
$result = array();
for ($i = 0; $i < $count; $i++) {
$result[$matches[1][$i]] = $matches[2][$i];
}
print_r($result[b]);
(output would be "some_text") (输出将是“some_text”)
If you are looking to extract all the values and store them in a dictionary as name/value pairs, you can use this:如果您想提取所有值并将它们作为名称/值对存储在字典中,您可以使用:
var regexp = /#(.*?)=(.*?)\//g;
var string = "sometext/#a=some_text/#b=25/moretext";
var match;
var result = {};
while ((match = regexp.exec(string)) != null) {
result[match[1]] = match[2];
}
alert(JSON.stringify(result));
Based on the limited information (you did not specify what characters can appear between #
and =
), here's what I think you're looking for:根据有限的信息(您没有指定在
#
和=
之间可以出现哪些字符),我认为您正在寻找以下内容:
var string = "sometext/#a=some_text/#b=25/moretext",
regex = /#([^=]+)=([^\/]+)/g,
matches = [],
match;
while (match = regex.exec(string)) {
matches.push(match[2]);
}
// matches -> ["some_text", "25"]
If you want to change the values in the string, you can do this with the same regex as before:如果要更改字符串中的值,可以使用与以前相同的正则表达式:
string = string.replace(regex, "#$1=new_value");
// -> "sometext/#a=new_value/#b=new_value/moretext"
To change the value of string改变字符串的值
var string = "sometext/#a=some_text/#b=25/moretext";
Regex.Replace(string,"(#a=).(/)",,"$1New Text$2");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.