1

I'm receiving urls in the following format:

http://www.whatever.com/maybesomthinghere/2323923723?what=what&who=no

I'd like some regex to grab "2323923723" from the URL. It may or may not have query string elements appended at the end.

0

4 Answers 4

4

If you have multiple numbers in a URL to extract:

url.scan(/\d+/)  # => ["2323923723"]

Or a single one:

url[/\d+/]       #=> "2323923723"
Sign up to request clarification or add additional context in comments.

Comments

0

You can always use str.delete like this:

num = str.delete("^0-9")

Output:

[7] pry(main)> str
=> "http://www.whatever.com/maybesomthinghere/2323923723?what=what&who=no\n"
[8] pry(main)> str.delete("^0-9")
=> "2323923723"

4 Comments

Hahaha... Power of Ruby..you misused :-)
Well ya @ArupRakshit everyone else is going to post the boring responses we all know - how about a curve ball! ;)
LoL...Enjoy the power of Ruby.
If next world war begins.. I will use Ruby's power full lambda ->() { } only.. :-)
0

If you simply want to capture any sequence of numbers out of the url, then this should work:

s = [url]
/[0-9]+/.match(s)

If you want to find a sequence of numbers bounded by / and ?, then you'd want something more like:

s = [url]
/\/([0-9]+)\?/.match(s)

You could be much more specific if you need to verify that you are working with a valid URL, if the numbers need to be bounded by more specific text, etc.

You may want to use rubular (http://rubular.com/) to test interactively.

Comments

0

Use this expression since the URL might contain other numbers after the ? (within the query string) or even before.

/(\d+)(?:\?)/

Demo

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.