分解以下代码以理解我的正则表达式和 gsub
理解:
str = "abc/def/ghi.rb"
str = str.gsub(/^.*\//, '')
#str = ghi.rb
^
: 字符串的开头
\/
: /
^.*\/
: /
在字符串中从开始到最后出现的所有内容
我的理解对吗?
.*
究竟是如何工作的?
最佳答案
您的一般理解是正确的。整个正则表达式将匹配 abc/def/
并且 String#gsub
将用空字符串替换它。
但是,请注意 String#gsub
不会就地更改字符串。这意味着 str
将包含替换后的原始值 ("abc/def/ghi.rb"
)。要就地更改它,您可以使用 String#gsub!
.
至于
.*
的工作原理——正则表达式引擎使用的算法称为 backtracking .由于 .*
是贪心的(会尝试匹配尽可能多的字符),您可以认为会发生这样的事情:
Step 1:
.*
matches the entire stringabc/def/ghi.rb
. Afterwards\/
tries to match a forward slash, but fails (nothing is left to match)..*
has to backtrack.
Step 2:.*
matches the entire string except the last character -abc/def/ghi.r
. Afterwards\/
tries to match a forward slash, but fails (/ != b
)..*
has to backtrack.
Step 3:.*
matches the entire string except the last two characters -abc/def/ghi.
. Afterwards\/
tries to match a forward slash, but fails (/ != r
)..*
has to backtrack.
...
Step n:.*
matchesabc/def
. Afterwards\/
tries to match a forward slash and succeeds. The matching ends here.
关于ruby - 如何理解 gsub(/^.*\//, '' ) 或正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395026/