Jonathan.Brink Jonathan.Brink - 29 days ago 7
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
    output:
    cat

  • input:
    @one: dog;
    output:
    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?

JsBin: http://jsbin.com/ludaqogexa/edit?js,console

Answer

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.

/^[^:]+:\s*([^;]+);?/;
Comments