Javascript string match for regex is not correct

Trying to apply regex to next line

Field "saveUserId" argument "idTwo" of type "String!" is required but not provided.

      

and came up with a RegExp pattern like

var rePattern = new RegExp(/Field (.)+ argument (.)+ of type (.)+ is required but not provided./);
var arrMatches = e.message.match(rePattern);
console.log(arrMatches[0]);
console.log(arrMatches[1]);

      

I'm expecting arrMatches [0] to output the "saveUserId" output and arrMatches [1] to output the "idTwo" output.

However, it returns instead

arrMatches[0] = Field "saveUserId" argument "idTwo" of type "String!" is required but not provided.
arrMatches[1] = "

      

+3


source to share


1 answer


You have two problems:

  • arrMatches[0]

    contains full match, groups are available from arrMatches[1]

    toarrMatches[1+n]

  • Your capture groups only contain 1 character: you want to include a quantifier within the group to avoid only capturing the last matched character; use (.+)

    instead(.)+



As Wiktor StribiΕΌew mentions the use of lazy quantifiers, there will be an optimization as this will avoid backtracking: without it, it .+

will match as much as possible (to the end of the line), then go back until the next tokens match, and when the .+?

next token is validated after matching each character .

.
Note that this is not an optimization that you can blindly apply; I think a good rule of thumb is to assess whether the end of your match is closer to the end of the text, in which case backtracking will be more efficient - or towards the start of the match, in which case the lazy quantifier will be more efficient.It all comes down to the amount of time. during which the next token (s) must be verified.

Better optimization, but if your fields would not contain any "

(escaped or not), they would have to match them using the negative symbol [^"]

instead .

, which would not match other than the quoted quotes.

+1


source







All Articles