+ 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...
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")
+ 3
Which of these is the same as the metacharacter '+'?
Answer :- {1,}
+ 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?).
+ 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.
+ 1
? means at the final one or zero times the code , but * Mac has 0 or more