Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top