Click here to Skip to main content
15,891,902 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
let text = "titanic";
let myRegex = /t[a-z]*i/; // Change this line
let result = text.match(myRegex); //gives "titani" -- why?


What I have tried:

looking for the '/t' explanations.
Posted
Updated 10-Mar-19 23:42pm

Because it matches.
"*" is "zero or more" so "ti" matches, but so does "titani".
If you want the shortest match, you have to tell the regex that:
/t[a-z]*?i/
 
Share this answer
 
Comments
Member 14105304 11-Mar-19 3:25am    
i mean why it did not give "titanic", c is included between a-z..?
OriginalGriff 11-Mar-19 4:17am    
Because your match expression ends with an "i" not a "c".
Regex is a *pattern matching* system - and your expression says "Match anything that starts with a 't', followed my zero or more of any alphabetic character, and ends with an 'i' - ignore anything after that".

Go here:
http://www.ultrapico.com/Expresso.htm
and get a copy of Expresso - it's free, and it examines, generates, and tests Regular expressions. It also tries to explain them in "near English" if you enter one. If you are going to play with Regexes, it's a godsend!
Member 14105304 11-Mar-19 4:29am    
ohhh.. it starts from 't' till 'i', i thought i is the flag..
gotch'a! thnx a lot! =]
OriginalGriff 11-Mar-19 4:50am    
You're welcome!
Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900