Skip to content

Use of \K when the string to match after \K can be empty #152

@learnbyexample

Description

@learnbyexample

Examples shown below tested with Ruby 2.7.1p83. In first example, the string to match after \K can be empty sometimes and in second example, it is always empty. When the match turns out to be empty, \K is failing to match the immediate next match.

# example 1
>> ',cat,tiger,dog'.gsub(/(?<=\A|,)[^,]*+/, '{\0}')
=> "{},{cat},{tiger},{dog}"
# note that 'dog' is matched because previous match wasn't empty
# but 'cat' fails to match, possibly because previous match was empty 
>> ',cat,tiger,dog'.gsub(/(?:\A|,)\K[^,]*+/, '{\0}')
=> "{},cat,{tiger},{dog}"

# example 2
>> 'abcd 123456'.gsub(/(?<=\w)/, ':')
=> "a:b:c:d: 1:2:3:4:5:6:"
>> 'abcd 123456'.gsub(/\w/, '\0:')
=> "a:b:c:d: 1:2:3:4:5:6:"
# every second word character is failing to be matched
>> 'abcd 123456'.gsub(/\w\K/, ':')
=> "a:bc:d 1:23:45:6"

This is different from the behavior seen with perl, vim (using \zs) and third-party regex module in python.

$ echo ',cat,tiger,dog' | perl -lpe 's/(?:\A|,)\K[^,]*+/{$&}/g'
{},{cat},{tiger},{dog}

$ echo 'abcd 123456' | perl -lpe 's/\w\K/:/g'
a:b:c:d: 1:2:3:4:5:6:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions