user3117575
user3117575

Reputation:

Regex returning uncaptured group instead of captured

I've run into a strange problem that I can't seem to get around... Basically, I've got this Regex that's returning the stuff that I don't have in a capture group, and it's not returning the actual captured group. Here is the Regex:

"localhost/a/b/c".match(/\/a\/b\/(.*?)/g);

To my knowledge, this is supposed to return ["c"]... But it returns:

["/a/b/"]

What am I doing wrong? I thought captured groups were supposed to be returned, not ignored.

Upvotes: 4

Views: 229

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

Try: "localhost/a/b/c".match(//a/b/(.+)/)[1]

In your original regex "localhost/a/b/c".match(/\/a\/b\/(.*?)/g);

  • the . means any character
  • the * means previous character class matched 0 - infinite times
  • the ? means to match as few of previously specified characters as possible while still matching the rest of the regex but since there is nothing after the group this group will effectively capture nothing
  • you dont seem to need the g modifier here at least not with this example.
  • access your matched group by its position in the returned array where [0] is the full match, [1] is the first capturing group, etc...

$('#myDiv').append( "localhost/a/b/c".match(/\/a\/b\/(.+)/)[1] );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><div>

Upvotes: 6

Related Questions