Curious_Bop Curious_Bop -5 years ago 129
Ruby Question

Return specific segment from Ruby regex

I have a big chunk of text I am scanning through and I am searching with a regex that is prefixed by some text.

var1 = textchunk.match(/thedata=(\d{6})/)

My result from
would return something like:


How do I only return the number part of the search so in the example above just 123456 without taking
and then stripping
off in a line below

Answer Source

If you expect just one match in the string, you may use your own code and access the captures property and get the first item (since the data you need is captured with the first set of unescaped parentheses that form a capturing group):


See this IDEONE demo

If you have multiple matches, just use scan:


NOTE: to only match thedata= followed with exactly 6 digits, add a word boundary:


or a lookahead (if there can be word chars after 6 digits other than digits):

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download