简体   繁体   English

Javascript正则表达式字符串之间的第一个括号包括内部括号

[英]Javascript Regex string between first brackets including inside brackets

I have string like this 我有这样的字符串

[test: test1: http://localhost?test=[1,2]]
[test: test2: http://localhost?test=[2,3]]

and I want to extract below from the text above 我想从上面的文字中提取以下内容

$1 = "test1"
$2 = "http://localhost?test=[1,2]"

$1 = "test2"
$2 = "http://localhost?test=[2,3]"

what I'm trying was 我正在尝试的是什么

/\[test:(.*?):(.*?)\]/

but it returns like this. 但它会像这样返回。 without "]" 没有“]”

$2 = "http://localhost?test=[2,3"

How can I change my regexp to get what I intented? 如何更改正则表达式以获得我的意图? thanks. 谢谢。

One fix to your regex would be to include the ] in the second group: 你的正则表达式的一个修复是在第二组中包含]

/\[test:(.*?):(.*?\])\]/
// add this ------^^

Another fix would be to have your existing \\] at the end of the regex only match if it is at the end of the string: 另一个修复方法是让正则表达式末尾的现有\\]匹配,如果它位于字符串的末尾:

/\[test:(.*?):(.*?)\]$/

As I guess, you get an URL as a second parameter. 我猜,你得到一个URL作为第二个参数。 It will be really not pretty easy to make a correct regex which will include all possible URL values. 制作一个包含所有可能的URL值的正确正则表达式真的不容易。

[test: test1: http://localhost?test=[1,2]]
[test: test1: http://localhost?test=[1,2]&somekey=somevalue]
[test: test1: http://localhost?test=[1,2]&answers=[1,2,3]]

You tried to find such regexp yourself. 你试图自己找到这样的正则表达式。 You came here, asked this question and spend so much of your expensive time trying to find a proper regular expression. 你来到这里,问了这个问题并花费了大量的时间来寻找合适的正则表达式。 And even if you now find such regular expression, did you really need it? 即使你现在找到这样的正则表达式,你真的需要吗?

As a popular quote says: 正如一句热门话题所说:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." 有些人在面对问题时会想“我知道,我会使用正则表达式”。
Now they have two problems. 现在他们有两个问题。

It is up to your choice, I can only recommend but there is an easy , fast way which works with any data given in an input: 这取决于您的选择,我只能推荐,但有一种简单快捷的方式可以与输入中给出的任何数据一起使用:

var str = "[test: test1: http://localhost?test=[1,2]]";
str = str.substring(1, str.length - 1);

var vals = str.split(': ');

console.log(vals[1]);
console.log(vals[2]);

No regular expressions, no headache. 没有正则表达,没有头痛。 I don't want to say "don't use regex", I want to say "don't use it when it is not required" :) 我不想说“不要使用正则表达式”,我想说“不要在不需要时使用它”:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM