Python re.search

后端 未结 2 1615
执念已碎
执念已碎 2020-12-09 18:03

I have a string variable containing

string = \"123hello456world789\"

string contain no spacess. I want to write a regex such that prints o

2条回答
  •  旧巷少年郎
    2020-12-09 18:23

    @InbarRose answer shows why re.search works that way, but if you want match objects rather than just the string outputs from re.findall, use re.finditer

    >>> for match in re.finditer(pat, string):
    ...     print match.groups()
    ...
    ('hello',)
    ('world',)
    >>>
    

    Or alternatively if you wanted a list

    >>> list(re.finditer(pat, string))
    [<_sre.SRE_Match object at 0x022DB320>, <_sre.SRE_Match object at 0x022DB660>]
    

    It's also generally a bad idea to use string as a variable name given that it's a common module.

提交回复
热议问题