0

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.

manish nautiyal
  • 2,556
  • 3
  • 27
  • 34

2 Answers2

3

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
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • 1
    Nice answer. I'd just like to add that if he needs to match upper and lowercase letters, he would need `[a-zA-Z]`. Cheers! – Sean Hill Dec 14 '12 at 10:06
  • 1
    @sean-hill Thanks! And I agree that `[a-zA-Z]` would probably be better, I just based my answer on the example which was all lowercase. – Chris Salzberg Dec 14 '12 at 15:30
  • Instead of '\*', a '+' might be better, as the '\*' would also match the string '{{}}'. – hd1 Dec 14 '12 at 15:48
2

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

ezkl
  • 3,829
  • 23
  • 39