如何将匹配的正则表达式作为字符串存储在变量中

时间:2021-02-11 14:02:16

Does anyone know how to take a matched regular expression as a string and store it in a variable? If my string is "police" and my regex matches it to get the result as "ice", how could I store "ice" in a variable? My guesses are the match, scan and to_s methods.

有谁知道如何将匹配的正则表达式作为字符串并将其存储在变量中?如果我的字符串是“警察”并且我的正则表达式匹配它以获得结果为“冰”,我怎么能在变量中存储“冰”?我的猜测是匹配,扫描和to_s方法。

I plan to use the stored string (using regex) to pass to a :prefix option in a tree interface method of the aws-sdk in RAILS to interact with aws-s3 objects.

我计划使用存储的字符串(使用正则表达式)在RAILS中的aws-sdk的树接口方法中传递给:prefix选项,以与aws-s3对象进行交互。

2 个解决方案

#1


1  

There are lots of ways to use regular expressions in Ruby. Using the match operator, you get a MatchData object, which can be turned into a String with the to_s method. If your regex doesn't match, you'll get nil instead of a MatchData object.

有很多方法可以在Ruby中使用正则表达式。使用匹配运算符,您将获得一个MatchData对象,该对象可以使用to_s方法转换为String。如果你的正则表达式不匹配,你将得到nil而不是MatchData对象。

my_match = /ice/.match("police");
my_var = my_match.to_s;

Or just do it all at once. If the regex doesn't match, you'll get an empty string.

或者只是一次完成。如果正则表达式不匹配,您将得到一个空字符串。

my_var = /ice/.match("police").to_s;

#2


0  

There are lots of choices, but:

有很多选择,但是:

my_variable = /ice/.match("police")[0]

will assign the matched expression to my_variable

将匹配的表达式分配给my_variable

#1


1  

There are lots of ways to use regular expressions in Ruby. Using the match operator, you get a MatchData object, which can be turned into a String with the to_s method. If your regex doesn't match, you'll get nil instead of a MatchData object.

有很多方法可以在Ruby中使用正则表达式。使用匹配运算符,您将获得一个MatchData对象,该对象可以使用to_s方法转换为String。如果你的正则表达式不匹配,你将得到nil而不是MatchData对象。

my_match = /ice/.match("police");
my_var = my_match.to_s;

Or just do it all at once. If the regex doesn't match, you'll get an empty string.

或者只是一次完成。如果正则表达式不匹配,您将得到一个空字符串。

my_var = /ice/.match("police").to_s;

#2


0  

There are lots of choices, but:

有很多选择,但是:

my_variable = /ice/.match("police")[0]

will assign the matched expression to my_variable

将匹配的表达式分配给my_variable