Regex returns one big match instead of multiple matches
Question:
I want to input :1: :2:
and get back 2 separate matches.
I used the regular expression :.+:
However, regex sees this as one singular match. Regex returns :1: :2:
instead of :1:
:2:
I am using the re library in Python
Answers:
‘+’ is a greedy match by default. Follow it with a ‘?’
Your regular expression :.+:
is known as greedy matching, i.e. it will attempt to match as many characters as possible. What you are looking for is lazy matching in regex. You can use this regular expression instead: :.+?:
.
I want to input :1: :2:
and get back 2 separate matches.
I used the regular expression :.+:
However, regex sees this as one singular match. Regex returns :1: :2:
instead of :1:
:2:
I am using the re library in Python
‘+’ is a greedy match by default. Follow it with a ‘?’
Your regular expression :.+:
is known as greedy matching, i.e. it will attempt to match as many characters as possible. What you are looking for is lazy matching in regex. You can use this regular expression instead: :.+?:
.