Click here to Skip to main content
15,891,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
let american = "color";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true -- why?


What I have tried:

to understand and try another examples. but still, i understand nothing
Posted
Updated 10-Mar-19 23:53pm

Because '?' on it's own (without '*' or '+' in front of it) says "zero or one" of the preceding element.
So "colou?r" matches either "color" or "colour" but not "colotr".

As I suggested last time, get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
It would have explained this to you!
 
Share this answer
 
v2
Comments
Member 14105304 11-Mar-19 5:52am    
so the '?' just dismiss the behind word of it and then checks?
OriginalGriff 11-Mar-19 6:00am    
No, read what I said:

'?' on it's own ... says "zero or one" of the preceding element.


Since the preceding element is a single character 'u' it says "zero or one 'u'"
To "disregard a word" you'd have to make it a group:
"(colou)?r" would match "colour" or "r" because "colou" is a group and that acts as the preceding element for the '?'

Seriously, download Expresso and try it - it will help you understand!
The u is optional in the regex, as denoted by the ?

So both 'color' and 'colour' will match.

Type colou?r in to the regex box on here to see:

Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
v2
Quote:
'? ' - Regular expression - js

Advice: read documentation.

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