本文介绍了如何理解gsub(/^.*\//,'')或正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分解下面的代码以了解我的正则表达式和gsub理解:

Breaking up the below code to understand my regex and gsub understanding:

str = "abc/def/ghi.rb"
str = str.gsub(/^.*\//, '')
#str = ghi.rb

^:字符串的开头

\/:/

^.*\/:从字符串中/开始到最后出现的所有内容

^.*\/ : everything from beginning to the last occurrence of / in the string

我对表达的理解正确吗?

Is my understanding of the expression right?

.*如何正常工作?

推荐答案

您的一般理解是正确的.整个正则表达式将匹配abc/def/,而String#gsub会将其替换为空字符串.

Your general understanding is correct. The entire regex will match abc/def/ and String#gsub will replace it with empty string.

但是,请注意 String#gsub 不会在适当位置更改字符串.这意味着str将在替换后包含原始值("abc/def/ghi.rb").要在适当位置进行更改,可以使用 .


关于.*的工作方式-正则表达式引擎使用的算法称为回溯.由于.*是贪婪的(将尝试匹配尽可能多的字符),因此您可以认为会发生以下情况:

However, note that String#gsub doesn't change the string in place. This means that str will contain the original value("abc/def/ghi.rb") after the substitution. To change it in place, you can use String#gsub!.


As to how .* works - the algorithm the regex engine uses is called backtracking. Since .* is greedy (will try to match as many characters as possible), you can think that something like this will happen:

这篇关于如何理解gsub(/^.*\//,'')或正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:27
查看更多