Just a little something that I am having trouble understanding.
I took the example from the instructions to codepen.io so I could mess around with it a bit to make sure I was grasping the concept properly of the ? character when lazy matching.
I began moving around the ? character to see what would happen and when I moved it to the end of the regex I thought there would be no difference in the match, but instead it returned “titanic” rather than “titani” .
I can only assume that the ? character stops after matching the character behind it ?
let ship = "titanic";
let regex = /t[a-z]*i?/; // why does this return "titanic" instead of just "titani"
let result = ship.match(regex);
console.log(ship.match(regex))
Also I might add this came up because my solution to the lesson itself was :
let myRegex = /<h.?1*>/;
//but It also accepted this :
let myRegex = /<h.1*?>/;
which led me to believe it made no difference where I put the ? character.
depending on where you put it, ? means zero or more characters
for example if you put as /colou?r/ this match both "color" and "colour"
you need to put the ? in front of one of the characters that say how many times to capture something, in that way you would have the lazy effect
this is “t followed by 0 or more [a-z] followed by 0 or 1 i”
this is “open angular bracket followed by h followed by one or zero any character followed by zero or more 1 followed by angular bracket”
this is “open angular bracket followed by any character followed by zero or more (lazy) 1”
the correct ways for this would be
/<.*?>/
or something like that
this mean “open angular bracket followed by zero or more (lazy) any character followed by closed angular bracket”
here you can see the effect of lazy matching because otherwise it would match until the > of the closing tag
I can understand this, as the angular bracket is specified in the regex.
I am just confused as to why this
/t[a-z]*i?/
would return [titanic] instead of [titani]. since in the lazy match regex the character c is not specified to match. Also from what I have read ? is supposed to return the smallest possible sub string that satisfies the regex pattern.
When using the regex /t[a-z]*i?/ wouldn’t [titani] be the smallest sub string of “titanic” ?