regular expression in ruby Regexp

156 Views Asked by At

I'm using ruby 1.9.2

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

Now I have to find {{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.

2

There are 2 best solutions below

3
Chris Salzberg On BEST ANSWER

You need to apend a * to the [a-z] 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:

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
0
ezkl On

The regular expression matching web application Rubular can be an incredibly helpful tool for doing realtime regular expression parsing.