AppTest AppTest - 4 months ago 11
Javascript Question

How do I make my limit match greedy?

The following code only matches

MN
. How do I get it to match
KDMN
?

var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."';
var patt = new RegExp("symbol.+([A-Z]{2,5})");
var res = patt.exec(str);
console.log(res[1]);

Answer

You may use a lazy +? quantifier:

/symbol.+?([A-Z]{2,5})/
         ^

See the regex demo. If you keep the greedy .+, it will match as many characters as possible, and will only leave the minimum 2 chars for the next subpattern.

Or, I'd rather make this a bit more verbose:

/symbol\s+"([A-Z]{2,5})/

See another regex demo. The symbol matches a literal string symbol, \s+ will match 1 or more whitespaces, " will match a double quote, and ([A-Z]{2,5}) will capture 2 to 5 uppercase ASCII letters into Group 1.

Comments