Jonathan.Brink Jonathan.Brink - 1 year ago 61
Javascript Question

Regex don't include match after captured group

I'm trying to extract variables from less css pre-processor source code file by using a regular expression, but my question can be asked more generally.

I need to craft a regular expression that works like this:

  • input:
    @one: cat

  • input:
    @one: dog;

Note the final semi-colon after 'dog' that I wish to not capture.

I have this almost working with:
new RegExp('^.*:\\s*(.*?);?');

But my final
isn't being excluded from the match

How do I make my selection be less greedy?


Answer Source

Making them "less greedy" is done by adding a ? after the quantifier as you did. The problem is that you haven't added an end anchor $ - if you add that your regex will work as expected. The behavior in that corner case depends on the regex engine; the .NET engine for instance would only match a single character in that case (d for the dog case) and stop.

However, this is not the solution IMHO. You should describe the pattern more precisely and then it will even work with the greedy matching.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download