0

Can anybody help me write a regular expression which could find all the instances of the following in a long string >

type="array" count="x" total="y"

where x and y could be any numbers from 1 to 100.

language is ruby.

1
  • How important is the "1 to 100" bit? Must it not match numbers bigger than 100 at all? Commented Jun 10, 2011 at 14:23

2 Answers 2

5

First, since we'll use the regex for a number twice, we'll save it as its own variable. Note that the number regex is comprised of three separate pieces: one-digit numbers, two-digit numbers, and three-digit numbers. This is a good rule of thumb to use when trying to make a regex to match a range of numbers. It's easy to get it wrong otherwise (allowing strings like "07").

Once you have the number regex, the rest is easy.

number = /[1-9]|[1-9][0-9]|100/
regex  = /type="array" count="#{number}" total="#{number}"/
string.scan(regex)
Sign up to request clarification or add additional context in comments.

8 Comments

@Jeff_Terrell The problem with the match is that you will just get the match object and that match object will only contains the first match and not all of the occurrences.
BTW, why are you upvoting this answer as it is right now. At least test it before please!
Good point, NeX. That wasn't what nEEbz asked for, was it? I've updated my code above. Thanks!
@Jeff_Terrell yup he was trying to "find all the instances". Looks much better now ;)
thanks; it works. can you tell me what exactly this notation do #{} ?
|
1

This will return an array of matches

long_string.scan(/type="array" count="(?:[1-9]\d?|100)" total="(?:[1-9]\d?|100)")

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.