GSUB 和正斜杠在 Ruby 中的使用

GSUB and Forward Slash usage in Ruby

我经常看到用正斜杠括起来的模式参数调用 gsub 函数。例如:

>> phrase = "*** and *** ran to the @@@."
>> phrase.gsub(/\*\*\*/, "WOOF")
=> "WOOF and WOOF ran to the @@@."

我认为这可能与转义星号有关,但使用单引号和双引号同样有效:

>> phrase = "*** and *** ran to the @@@."
>> phrase.gsub('***', "WOOF")
=> "WOOF and WOOF ran to the @@@."

>> phrase.gsub("***", "WOOF")
=> "WOOF and WOOF ran to the @@@."

使用正斜杠只是惯例吗?我错过了什么?

如果需要使用正则表达式,请使用正斜杠。

如果您将字符串参数与 gsub 一起使用,它只会进行普通字符匹配。

在您的示例中,在使用正则表达式时需要反斜杠来转义星号,因为星号在正则表达式中具有特殊含义(可选择匹配任意次数)。使用字符串时不需要它们,因为它们只是完全匹配。

在您的示例中,您可能不需要使用正则表达式,因为它是一个简单的模式。但是,如果您想匹配 *** 仅当它位于字符串的开头时(例如您示例中的第一串),那么您需要使用正则表达式,例如:

phrase.gsub(/^\*{3}/, "WOOF")

有关正则表达式的更多信息,请参阅:http://www.regular-expressions.info/

有关在 Ruby 中使用正则表达式的更多信息,请参阅:http://ruby-doc.org/core-2.2.0/Regexp.html

要在 Ruby 中使用正则表达式,请尝试:http://rubular.com/

您未阅读文档:

The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\d' will match a backlash followed by ‘d’, instead of a digit.

http://ruby-doc.org/core-2.1.4/String.html#method-i-gsub

换句话说,你可以给出一个字符串或者一个正则表达式。正则表达式可以用几种方式分隔:

Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

http://ruby-doc.org/core-2.2.2/Regexp.html

%r 和备用 %r 定界符的好处是您通常可以找到一个不与模式中的字符冲突的定界符,这将强制转义它们,就像在您的例子。

* 必须转义,因为它在正则表达式中具有特殊含义,但在字符串中却没有。