Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
learnbyexample opened this issue Aug 19, 2020 · 0 comments
Open

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

learnbyexample opened this issue Aug 19, 2020 · 0 comments

Comments

@learnbyexample
Copy link

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:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant