How to make Regex choose words separately

后端 未结 2 1655
醉话见心
醉话见心 2021-01-25 06:49

So I have this string:

sockcooker!~shaz@Rizon-AC7BDF2F.dynamic.dsl.as9105.com !~shaz@ PRIVMSG #Rizon :ohai. New here. registered 10 mins ago, have not got an ema         


        
相关标签:
2条回答
  • 2021-01-25 07:32

    You want to use an ungreedy match. There are two ways (and python supports both). The latter is more flexible:

    r"![^@]+"
    r"!.+?@
    

    The ? makes the .+ ungreedy, so it will stop at the first "@" instead of the last.

    0 讨论(0)
  • 2021-01-25 07:48

    By default, quantifiers are greedy in nature in the sense, they will try to match as much as they can. That is why your regex is matching till the last @.

    You can use reluctant quantifier (add a ? after the +) to stop at the first @:

    r"!.+?@"
    

    Or you can also use negated character class, which will automatically stop at the first @:

    r"![^@]+"
    

    Choose whatever is easier to understand for you.

    0 讨论(0)
提交回复
热议问题