Difference between * and ? metacharacters??? THANKS 😀😃😀😄 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Difference between * and ? metacharacters??? THANKS 😀😃😀😄

What the difference between * and ? then??? BOTH seem to match 0 or more occurrences of the preceding expression. In the code example (the one for 2nd last slide of the More Metacharacters lesson), you get the SAME output if you replace the ? with *, so it's not really clear...

26th Aug 2016, 6:07 PM
Krishna Limani
Krishna Limani - avatar
5 Answers
+ 8
As it says in the lesson, * matches zero or MORE of the last thing, whereas ? matches zero or ONE. It's only apparent when ? isn't used at the end of the pattern string. Try this code, try changing the number of 2's or change ? into * and the difference will be apparent. import re pattern = r"11(2)?33" if re.match(pattern, "112233"): print ("match") else: print ("no")
26th Aug 2016, 9:26 PM
Doc
Doc - avatar
+ 3
Which of these is the same as the metacharacter '+'? Answer :- {1,}
29th Jun 2020, 5:57 AM
Gourav Tomar
Gourav Tomar - avatar
+ 2
You can remember it this way: * — any number of times (it is common to point any or all by *, examples: RegEx (as mentioned many times in this thread), Windows "open"/"save as" window ("*.txt" — filter for any file with "txt" extension; "*.*" — show all files in this directory), statement of importing in Python ("from module import *" — import every name from "module" that does not start with _), Google Search (placeholder for an unknown/any word)). ? — whether occurs or not (occurs?).
30th May 2021, 3:38 AM
#0009e7 [get]
#0009e7 [get] - avatar
+ 1
As per the docs, "*" Matches 0 or more (greedy) repetitions of the preceding RE. Greedy means that it will match as many repetitions as possible. "?" Matches 0 or 1 (greedy) of the preceding RE. Notice "*" matches 0 or MORE, while "?" matches 0 or 1. Doc provides a wonderful example to illustrate.
2nd Sep 2016, 9:35 AM
Somdeep Datta
Somdeep Datta - avatar
+ 1
? means at the final one or zero times the code , but * Mac has 0 or more
31st Jan 2017, 7:39 PM
The Guayguy
The Guayguy - avatar