简体   繁体   中英

Strange RegExp behavior in JavaScript

I need to capture every %{string} sequience in a string. I am created a RegExp: /[^%]*(%{[^}]+})?/g , which works correctly on string Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer} on regex101.com ( https://regex101.com/r/aB2xL5/1 ), but incorrect in JS: var a='Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}'.match(/[^%]*(%{[^}]+})?/g);
console.log(a); //['Lorem %{ipsum}', ' dolor %{sit}', ' amet adipiscing aenean %{consectetuer}', '']
var a='Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}'.match(/[^%]*(%{[^}]+})?/g);
console.log(a); //['Lorem %{ipsum}', ' dolor %{sit}', ' amet adipiscing aenean %{consectetuer}', '']
var a='Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}'.match(/[^%]*(%{[^}]+})?/g);
console.log(a); //['Lorem %{ipsum}', ' dolor %{sit}', ' amet adipiscing aenean %{consectetuer}', '']
What i am doing wrong?

What i need: Input string: 'abc %{def} ghi %{jkl}' Output array: ['%{def}','%{jkl}']

As said in the comments, don't access the whole match which, even on regex101, contains more than you need, but rather access the first group of the match.

To do so, use Regex.prototype.exec instead of String.prototype.match :

var regex=/[^%]*(%{[^}]+})?/g;
var data='Lorem %{ipsum} dolor %{sit} amet adipiscing aenean %{consectetuer}';
var result=[];
var match;
while (match = regex.exec(data)) {
  result.push(match[1]);  // match the first group of the result
}

Edit : I just saw Thomas' comment, which is much better than this solution. I'll leave it here because it does indeed solve your problem and explains how to capture groups, but you should use his regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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