0

I have the following and am trying to split on '.' and then split the returned first part on '-' and return the last of the first part. I want to return 447.

a="cat-vm-447.json".split('.').split('-')

Also, how would I do this as a regular expression? I have this:

a="cat-vm-447.json".split(/-[\d]+./)

but this is splitting on the value. I want to return the number.

I can do this:

a="cat-vm-447.json".slice(/[\d]+/)

and this gives me back 447 but would really like to specify that the - and . surround it. Adding those in regex return them.

0

5 Answers 5

3

First question. Split returns an array, so you need to use Array#[] to get first(0) or last(-1) elements of this array. Alternatives is Array#first and Array#last methods.

a="cat-vm-447.json".split('.')[0].split('-')[-1] # => "447"

Second question. You can match your number into group and then get it from the response (it will have index 1. Item with index 0 will be full match ("-447." in your case). You can use String#[] or String#match (among others) methods to match your regex.

"cat-vm-447.json"[/-(\d+)\./, 1] # => "447"
# or
"cat-vm-447.json".match(/-(\d+)\./)[1] # => "447"
Sign up to request clarification or add additional context in comments.

2 Comments

If the filename is guaranteed to only have one string of digits, "cat-vm-447.json"[/\d+/] will return "447" without the need to use a capture.
@theTinMan, yes, but OP would really like to specify that the - and . surround it (from the question)
1

Split returns an array, so you need to specify the index for the next split.

a="cat-vm-447.json".split('.').first.split('-').last

For the regular expression, you need to wrap what you want to capture in parentheses.

/-(\d+)\./

Comments

0
a = "cat-vm-447.json"
b = a.match(/-(\d+)\./)
p b[0] # => 447 

Comments

0

Try something like that:

if "cat-vm-447.json" =~ /([\d]+)/
   p $1
else
   p "No matches"
end

The parentheses in the regex extract the result in the $1 variable.

Comments

0

When you split your string second time, you actually trying to split Array instead of String.

ruby-1.9.3-head :003 > "cat-vm-447.json".split('.')
# => ["cat-vm-447", "json"] 

In regexp case, you can use /[-.]/

ruby-1.9.3-head :008 > "cat-vm-447.json".split(/[-.]/)
# => ["cat", "vm", "447", "json"] 
ruby-1.9.3-head :009 > "cat-vm-447.json".split(/[-.]/)[2]
# => "447" 

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.