Curious_Bop Curious_Bop - 5 months ago 9
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
var1
would return something like:

thedata=123456


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

Answer

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):

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

See this IDEONE demo

If you have multiple matches, just use scan:

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

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

/thedata=(\d{6})\b/
                ^^

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

/thedata=(\d{6})(?!\d)/
                ^^^^^^
Comments