DEV Community

Randy Rivera
Randy Rivera

Posted on

Regular Expressions Notes(2)

Match Characters that Occur Zero or More Times

  • The last challenge used the plus + sign to look for characters that occur one or more times. There's also an option that matches characters that occur zero or more times.
  • The character to do this is the asterisk or star: *.
  • For this post, chewieQuote has been initialized as the string Aaaaaaaaaaaaaaaarrrgh! Let's Create a regex chewieRegex that uses the * character to match an uppercase A character immediately followed by zero or more lowercase a characters in chewieQuote. Your regex does not need flags or character classes, and it should not match any of the other quotes.
let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!";
let chewieRegex = /Aa*/;
let result = chewieQuote.match(chewieRegex);

console.log(result); will display [ 'Aaaaaaaaaaaaaaaa' ]
Enter fullscreen mode Exit fullscreen mode

Find Characters with Lazy Matching

  • In regular expressions, a greedy match finds the longest possible part of a string that fits the regex pattern and returns it as a match. The alternative is called a lazy match, which finds the smallest possible part of the string that satisfies the regex pattern.
  • You can apply the regex /t[a-z]*i/ to the string "titanic". This regex is basically a pattern that starts with t, ends with i, and has some letters in between.
  • Regular expressions are by default greedy, so the match would return ["titani"]. It finds the largest sub-string possible to fit the pattern.
  • However, you can use the ? character to change it to lazy matching. "titanic" matched against the adjusted regex of /t[a-z]*?i/ returns ["ti"].

  • Let's Fix the regex /<.*>/ to return the HTML tag <h1> and not the text "<h1>Winter is coming</h1>".

  • Remember the wildcard . in a regular expression matches any character.

let text = "<h1>Winter is coming</h1>";
let myRegex = /<.*>/; // Change this line
let result = text.match(myRegex);
Enter fullscreen mode Exit fullscreen mode
  • Answer:
let text = "<h1>Winter is coming</h1>";
let myRegex = /<.*?>/; 
let result = text.match(myRegex);

console.log(result); will display [ "<h1>" ]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

olayinkaspec profile image
Olayinka Dada

Hi! could please explain details how you arrived at this answer? Thank you.