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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

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 Thanks! And I agree that [a-zA-Z] would probably be better, I just based my answer on the example which was all lowercase.
Instead of '*', a '+' might be better, as the '*' would also match the string '{{}}'.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.