尝试在ruby中使用正则表达式来查找特定字符

时间:2021-07-06 11:48:25

I am trying to use regular expressions in a ruby on rails app to search through a given string and find any instances of opening and closing square brackets, (ie [ and ]) and select the contents between the two.

我试图在rails应用程序的ruby中使用正则表达式来搜索给定的字符串并找到打开和关闭方括号的任何实例(即[和])并选择两者之间的内容。

For example:

例如:

Lorem ipsum [dolor sit] amet...

In this string the result would be: [dolor sit]

在这个字符串中,结果将是:[dolor sit]

I played around with rubular a bit and found that this more or less does what I want

我玩了一些rubular,发现这或多或少做了我想要的

/\[.*?\]/

So my question is, how do i match everything within the two square brackets without selecting the brackets themselves? And also how do I actually integrate them into a ruby script?

所以我的问题是,如何在不选择括号本身的情况下匹配两个方括号内的所有内容?而且我如何实际将它们集成到ruby脚本中?

Regular expressions are totally new ground for me so any help you guys can offer would be much appreciated :)

正则表达式对我来说是一个全新的基础,所以你们提供的任何帮助都会非常感激:)

3 个解决方案

#1


4  

Collecting multiple captures of a regexp is a job for String#scan

收集正则表达式的多个捕获是String#scan的工作

>> s="Lorem ipsum [dolor sit] [amet] ..."
=> "Lorem ipsum [dolor sit] [amet] ..."
>> s.scan(/\[([^\]]*)\]/).flatten
=> ["dolor sit", "amet"]

#2


2  

You need to use String#scan:

你需要使用String#scan:

"Hi [there] how are [you]?".scan(/\[.*?\]/)
 => ["[there]", "[you]"] 

This method iterates the entire string, returning every match.

此方法迭代整个字符串,返回每个匹配项。

#3


1  

You can wrap the part of the Regex that corresponds to the part of the input that you want to extract inside ():

您可以将与要提取的输入部分对应的Regex部分包装在内部():

str = "Lorem ipsum [dolor sit] amet....".match(/\[(.*?)\]/)
# str --> #<MatchData "[dolor sit]" 1:"dolor sit"> 
str[1] # Will give you 'dolor sit'

Note that you can also access the result of the matching via the global variable: $1 (in general $i where i represents the index of the matching word).

请注意,您还可以通过全局变量访问匹配的结果:$ 1(通常为$ i,其中i表示匹配单词的索引)。

#1


4  

Collecting multiple captures of a regexp is a job for String#scan

收集正则表达式的多个捕获是String#scan的工作

>> s="Lorem ipsum [dolor sit] [amet] ..."
=> "Lorem ipsum [dolor sit] [amet] ..."
>> s.scan(/\[([^\]]*)\]/).flatten
=> ["dolor sit", "amet"]

#2


2  

You need to use String#scan:

你需要使用String#scan:

"Hi [there] how are [you]?".scan(/\[.*?\]/)
 => ["[there]", "[you]"] 

This method iterates the entire string, returning every match.

此方法迭代整个字符串,返回每个匹配项。

#3


1  

You can wrap the part of the Regex that corresponds to the part of the input that you want to extract inside ():

您可以将与要提取的输入部分对应的Regex部分包装在内部():

str = "Lorem ipsum [dolor sit] amet....".match(/\[(.*?)\]/)
# str --> #<MatchData "[dolor sit]" 1:"dolor sit"> 
str[1] # Will give you 'dolor sit'

Note that you can also access the result of the matching via the global variable: $1 (in general $i where i represents the index of the matching word).

请注意,您还可以通过全局变量访问匹配的结果:$ 1(通常为$ i,其中i表示匹配单词的索引)。