0

I have a string:

'my_array1: ["1445","374","1449","378"], my_array2: ["1445","374", "1449","378"]'

I need to match all sets of digits from my_array2: [...] and count how many of them there.

I need to do something like this with regex and ruby MatchData

string = 'my_array1: ["1445","374", "1449","378"], my_array2: ["1445","374", "1449","378"]'
matches = string.match(/my_array2\:\s[\[,]\"(\d+)\"/)
count_matches = matches.size

Expected result should be 4. What is the correct way of doing it?

4
  • 1
    I would use this regex to match the digit-only arrays. It won't work with mixed type arrays. Oct 12, 2015 at 7:51
  • Your string is invalid. You haven't escaped " correctly. It is not clear what it means.
    – sawa
    Oct 12, 2015 at 8:33
  • This smells like an XY-question. Where does that string come from?
    – sawa
    Oct 12, 2015 at 8:34
  • I just changed that string to single quotes
    – arthur-net
    Oct 12, 2015 at 8:51

1 Answer 1

0

If you are guaranteed that the content of my_array2 is always numeric you could simply use split twice. First you splitby my_array2: [" and then split by ,. This should give you the amount of items you are after.

If you are not guaranteed that, you could still split by my_array2 and instead of splitting again, you use a pattern such as "\d+" (or "\d+(\.\d+)? if you have floating point values) and count.

An example of the expression is available here.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.