JavaScript 中的 preg_match ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3291289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
preg_match in JavaScript?
提问by hsz
Is it possible in JavaScriptto do something like preg_matchdoes in PHP?
是否有可能JavaScript做像preg_matchin那样的事情PHP?
I would like to be able to get two numbers from string:
我希望能够从字符串中获取两个数字:
var text = 'price[5][68]';
into two separated variables:
分成两个独立的变量:
var productId = 5;
var shopId = 68;
Edit:
I also use MooToolsif it would help.
编辑:MooTools如果有帮助,我也会使用。
回答by godswearhats
回答by kander
var text = 'price[5][68]';
var regex = /price\[(\d+)\]\[(\d+)\]/gi;
match = regex.exec(text);
match[1] and match[2] will contain the numbers you're looking for.
match[1] 和 match[2] 将包含您要查找的数字。
回答by Tracey Turn
var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
if(!thisRegex.test(text)){
alert('fail');
}
I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.
我发现 test 表现得更多 preg_match 因为它提供了一个布尔返回。但是,您必须声明一个 RegExp 变量。
TIP: RegExp adds it's own / at the start and finish, so don't pass them.
提示:RegExp 在开始和结束时添加它自己的 /,所以不要传递它们。
回答by Dan Stocker
This should work:
这应该有效:
var matches = text.match(/\[(\d+)\][(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];
回答by Tim Pietzcker
var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
var productId = match[1];
var shopId = match[2];
} else {
// no match
}
回答by Zafer BAHADIR
Sample code to get image links within HTML content. Like preg_match_allin PHP
在 HTML 内容中获取图像链接的示例代码。像PHP 中的preg_match_all
let HTML = '<div class="imageset"><table><tbody><tr><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg" class="fr-fic fr-dii"></td><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg" class="fr-fic fr-dii"></td></tr></tbody></table></div>';
let re = /<img src="(.*?)"/gi;
let result = HTML.match(re);
out array
出阵列
0: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg""
1: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg""

