Regex to find text between special characters

时间:2016-12-02 05:12:47

标签: javascript regex

Man, I'm confused. I've been looking at a million questions like these, but none of the answers work even if I simplify.

I want to capture text between $[ and ].

Why doesn't \$\[.*\] work? Even if I follow guides for square brackets only it doesn't work.

Jsfiddle to show that it doesn't work.

const content = "[Hey] (Ho) [f(1)]"
const example1 = '\[.*\]'
const example2 = '\[(.*?)\]'
const regex1 = new RegExp(example1, "g")
const regex2 = new RegExp(example2, "g")
const newText1 = content.replace(regex1, "EXAMPLE1")
const newText2 = content.replace(regex2, "EXAMPLE2")
console.log(newText1) //Prints [Hey] (Ho) [f(1)]
console.log(newText2) //Prints [Hey] EXAMPLE2HoEXAMPLE2 [fEXAMPLE21EXAMPLE2]

2 个答案:

答案 0 :(得分:1)

You want to use the following regex to obtain multiple matches in your input string:

\$\[(.*?)\]

Note carefully that the capture group is (.*?). The question mark makes the match non greedy, meaning it will stop after hitting the nearest closing bracket.

var string = "stuff $[stuff] hello world $[123] blah [abc] $[def] blah";

var regex = new RegExp(/\$\[(.*?)\]/g);
var myArray;

while ((myArray = regex.exec(string)) != null) {
    alert(myArray[1])
}

If you had used the untempered (.*) as the capture group, there would have been only a single match starting from the first opening bracket and ending with the last closing bracket; clearly not what you intended.

Demo here:

JSFiddle

答案 1 :(得分:0)

use with sub string :/\$\[(.*)\]/ .And apply with exec

Demo regex

var res=/\$\[(.*)\]/g.exec("$[and]");
console.log(res)
console.log(res[1])