1

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

2 Answers 2

1

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

Comments

0
▶ textchunk = 'garbage=42 thedata=123456'
#⇒ "garbage=42 thedata=123456"
▶ textchunk[/thedata=(\d{6})/, 1]
#⇒ "123456"
▶ textchunk[/(?<=thedata=)\d{6}/]
#⇒ "123456"

The latter uses positive lookbehind.

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.