Regex to get all character to the right of first space?

前端 未结 4 497
时光说笑
时光说笑 2021-01-14 21:05

I am trying to craft a regular expression that will match all characters after (but not including) the first space in a string.

Input text:

foo bar b         


        
相关标签:
4条回答
  • 2021-01-14 21:13

    You don't need look behind.

    my $str = 'now is the time';
    # Non-greedily match up to the first space, and then get everything after in a group.
    $str =~ /^.*? +(.+)/; 
    my $right_of_space = $1; # Keep what is in the group in parens
    print "[$right_of_space]\n";
    
    0 讨论(0)
  • 2021-01-14 21:21

    You can also try this

    (?s)(?<=\S*\s+).*
    

    or

    (?s)\S*\s+(.*)//group 1 has your match
    

    With (?s) . would also match newlines

    0 讨论(0)
  • 2021-01-14 21:28

    I'd prefer to use [[:blank:]] for it as it doesn't match newlines just in case we're targetting mutli's. And it's also compatible to those not supporting \s.

    (?<=[[:blank:]]).*
    
    0 讨论(0)
  • 2021-01-14 21:32

    You can use a positive lookbehind:

    (?<=\s).*
    

    (demo)

    Although it looks like you've already put a capturing group around .* in your current regex, so you could just try grabbing that.

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