简体   繁体   中英

Regex capturing : get the whole match in a capturing group

I can't get this capture to work as I would like :

My aim is to capture in a string the length of the first capture group :

var regex = /(_)?;([\w]+);([\w]+);/;
var string = "____;foo;bar;";
var matches = regex.exec(string);

console.log(matches); // outputs  ["_;foo;bar;", "_", "foo", "bar"]

As you can see, matches[1] contains the capturing group for undescores, but gives me the matched character, not all underscores. What i expect would be this result :

["_;foo;bar;", "_____", "foo", "bar"]

Is there a way to achieve this with a regex ? I would prefer avoid splitting the string with ; ...

You could use a pattern like this:

/(_*);(\w+);(\w+);/

Which will give you:

["_____;foo;bar;", "_____", "foo", "bar"]

This pattern will match the following sequence:

  • zero or more underscores, captured in group 1
  • a semicolon
  • one or more word characters, captured in group 2
  • a semicolon
  • one or more word characters, captured in group 3
  • a semicolon

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