简体   繁体   English

红宝石正则表达式中的正则表达式

[英]regular expression in ruby Regexp

I'm using ruby 1.9.2 我正在使用ruby 1.9.2

string = "asufasu isaubfusabiu safbsua fbisaufb sa {{hello}} uasdhfa s asuibfisubibas {{manish}} erieroi"

Now I have to find {{anyword}} 现在我必须找到{{anyword}}

How many times it will come and the name with curly braces. 它会出现多少 ,并带有大括号名称

After reading Regexp 看完正则表达式

I am using 我在用

/{{[a-z]}}/.match(string) 

but it return nil everytime. 但每次都会返回nil。

You need to apend a * to the [az] pattern to tell it to match any number of letters inside the { s, and then use scan to get all occurrences of the match in the string: 您需要在[az]模式后面加上* ,以告诉它匹配{ s内的任意数量的字母,然后使用scan来获取字符串中所有匹配项:

string.scan(/{{[a-z]*}}/)
=> ["{{hello}}", "{{manish}}"]

To get the number of times matches occur, just take the size of the resulting array: 要获得匹配发生的次数,只需取结果数组的大小即可:

string.scan(/{{[a-z]*}}/).size
=> 2

正则表达式匹配的Web应用程序Rubular对实时进行正则表达式解析可能是非常有用的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM