Regex to extract substring, returning 2 results for some reason

后端 未结 5 1374
情话喂你
情话喂你 2020-11-28 08:13

I need to do a lot of regex things in javascript but am having some issues with the syntax and I can\'t seem to find a definitive resource on this.. for some reason when I d

5条回答
  •  春和景丽
    2020-11-28 08:14

    Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)

    var source = "afskfsd33j"
    var result = source.match(/a(.*)j/);
    
    result: ["afskfsd33j", "fskfsd33"]
    

    The reason why you received this exact result is following:

    First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".

    Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".

    If you want to get rid of second value in array you may define pattern like this:

    /a(?:.*)j/
    

    where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.

    Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:

    /a.*j/
    

    If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:

    var result = /a.*j/.test(source);
    

    The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml

提交回复
热议问题