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

标签 ruby regex gsub

分解以下代码以理解我的正则表达式和 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/

相关文章:

ruby-on-rails - Bundler 正在从 Gemfile.lock 中删除 RUBY VERSION

ruby - 如何在 Test Kitchen 中获取加密数据包 secret 的值

java - 正则表达式更新日期精度

ruby - 如何以编程方式删除图像的背景,使其在 ruby​​ 中透明?

Ruby 术语问题 : Is this a Ruby declaration, 定义和赋值,同时进行?

c# - 用于输入验证的正则表达式白名单 - 重音不敏感

Java split 在结果中返回空格

使用 gsub 的 Ruby 正则表达式

仅使用 gsub 替换表达式以外的所有字符

r - 在数据帧上使用 gsub()