gpt4 book ai didi

ruby - 如何理解 gsub(/^.*\//, '' ) 或正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:39 27 4
gpt4 key购买 nike

分解以下代码以理解我的正则表达式和 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 string abc/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: .* matches abc/def. Afterwards \/ tries to match a forward slash and succeeds. The matching ends here.

关于ruby - 如何理解 gsub(/^.*\//, '' ) 或正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com