最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript and RegEx: match function returns an array - Stack Overflow

programmeradmin0浏览0评论

I have a string:

var doi_id= "10.3390/metabo1010001"

And I would like to match only the first serie of digits from the end.

For that, I am using this regEx:

var doinumericpart = doi_id.match(/(\d*)$/);

The "problem" (or not) is that doinumericpart returns

1010001,1010001

instead of 1010001 and I don't know why.

When I am trying this regex here: everything seems to work fine.

Thank you very much for the help.

I have a string:

var doi_id= "10.3390/metabo1010001"

And I would like to match only the first serie of digits from the end.

For that, I am using this regEx:

var doinumericpart = doi_id.match(/(\d*)$/);

The "problem" (or not) is that doinumericpart returns

1010001,1010001

instead of 1010001 and I don't know why.

When I am trying this regex here: http://regexr.?31htm everything seems to work fine.

Thank you very much for the help.

Share Improve this question asked Jul 16, 2012 at 14:48 Milos CuculovicMilos Cuculovic 20.3k54 gold badges164 silver badges276 bronze badges 1
  • try removing the parentheses after \d* and just have \d*$ – Hunter McMillen Commented Jul 16, 2012 at 14:52
Add a ment  | 

3 Answers 3

Reset to default 8

match() returns an array like it's supposed to. The first element is the whole substring that matched the pattern, then the first one onwards contain the subpatterns.

In your case, just get rid of the () - you don't need them since they enclose the whole pattern.

var doinumericpart = doi_id.match(/\d*$/)[0];

The [0] dereferences the array to give you the exact element you want.

match returns either null or an array of the matches. The amount of matches depends on how many capturing groups you have in your regex. The item at [1] will be your match so you can do:

var doinumericpart = doi_id.match(/(\d*)$/)[1]; //Access second item in the matches array

match returns the plete match and each capturing group or null if there were no matches.

This is useful if you want to provide some context:

"10.3390/metabo1010001".match(/metabo(\d*)/)
// => ["metabo1010001", "1010001"]
  • metabo1010001 is the whole match
  • 1010001 is the first capturing group
发布评论

评论列表(0)

  1. 暂无评论