简体   繁体   中英

javascript regex — only produces last letter in (.)+ group?

I am trying to split a string by regex and getting an unexpected result:

var str = 'name == abcd';
var pattern = /([^!=>< ]+)\s*([!=><]+)\s*(.)+/i;

pattern.exec(str);

the result of the example is : [ "name == abcd", "name", "==", **"d"** ]

why "d" and not "abcd" ?

The capturing group (.) only captures one character. The construct (.)+ means "one or more capturing groups, each containing one character". It returns only "d" because that is the last iteration of the capturing group encountered.

If you move the repetition inside the capturing group, (.+) , you will then have asked for "a capturing group containing one or more characters". This is probably what you want.

var pattern = /([^!=>< ]+)\s*([!=><]+)\s*(.+)/i;

将最后一个+移到括号中:

var pattern = /([^!=>< ]+)\s*([!=><]+)\s*(.+)/i;

Because last pair of parentheses captures only last match. Move + into parentheses: /([^!=>< ]+)\\s*([!=><]+)\\s*(.+)/i;

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