My String looks like this:
"Jothijohnsamyperiyasamy"
I want only "Jothijohnsamy"
from the above string. The Regular expression,
'Jo\w+samy'
prints "Jothijohnsamyperiyasamy"
, but I want only "Jothijohnsamy"
. Any Ideas?
My String looks like this:
"Jothijohnsamyperiyasamy"
I want only "Jothijohnsamy"
from the above string. The Regular expression,
'Jo\w+samy'
prints "Jothijohnsamyperiyasamy"
, but I want only "Jothijohnsamy"
. Any Ideas?
Try non-greedy match:
>>> re.compile(r"Jo\w+?samy").match("Jothijohnsamyperiyasamy")
<_sre.SRE_Match object; span=(0, 13), match='Jothijohnsamy'>
>>> _.group()
'Jothijohnsamy'
The +?
token means "match 1 or more times, but as few as possible. Without the question mark it means "match 1 or more times, as many as possible".
Another straightforward example: For the string "aaaaaa"
, the regex a+
matches all characters, but a+?
matches only one (as few as possible), and a*?
matches none.