简体   繁体   English

如何对方括号进行正则表达式?

[英]How to regex square brackets?

The problem: I want to get all of the square brackets' content, and then delete them, but only if the brackets are at the beginnig of the string. 问题:我想获取所有方括号的内容,然后删除它们,但前提是方括号位于字符串的开头。

For example, a given string [foo][asd][dsa] text text text will return array with all of the three brackets' content ( ["foo", "asd", "dsa"] ), and the string will become text text text . 例如,给定的字符串[foo][asd][dsa] text text text将返回包含三个方括号的所有内容的数组( ["foo", "asd", "dsa"] ),该字符串将变为text text text

But if the string looks like that: [foo] text [asd][dsa] text text , it'll take only the [foo] , and the string will become: text [asd][dsa] text text . 但是,如果字符串看起来像这样: [foo] text [asd][dsa] text text ,它将仅使用[foo] ,字符串将变成: text [asd][dsa] text text

How can I do that using JavaScript? 如何使用JavaScript做到这一点?

The loop checks the start of the string for anything in square brackets, takes the contents of the brackets, and removes the whole lot from the start. 循环检查字符串的开头是否有方括号,取出括号中的内容,并从开头删除整批内容。

var haystack = "[foo][asd][dsa] text text text";
var needle = /^\[([^\]]+)\](.*)/;
var result = new Array();

while ( needle.test(haystack) ) {  /* while it starts with something in [] */
    result.push(needle.exec(haystack)[1]);       /* get the contents of [] */
    haystack = haystack.replace(needle, "$2"); /* remove [] from the start */
}

var newstring = oldstring.replace(/\\[\\w{3}]/, "");

You could proceed using a while, taking the first, adding it to an array, remove it and then do all again. 您可以继续使用一段时间,先进行一遍,然后将其添加到数组中,然后将其删除,然后再进行全部操作。 This would give this : 这将给出:

var t1 = "[foo][asd][dsa] text text text";
var rule = /^(?:\[([^\]]*)\])/g;
var arr = new Array();

while(m = rule.exec(t1)){
    arr.push(m[1]);
    t1 = t1.replace(rule, "")
}

alert(arr); // foo,asd,dsa
alert(t1);  //  text text text

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

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