-1

I have this string like "682_2, 682_3, 682_4". (682 is a random number)

How can i get this string "2, 3, 4" using regex and ruby?

Stefan
  • 96,300
  • 10
  • 122
  • 186
lumosnysm
  • 13
  • 4

3 Answers3

2

You can do this in ruby

input="682_2, 682_3, 682_4"
output = input.gsub(/\d+_/,"")
puts output
Hemang
  • 813
  • 8
  • 18
0

A simple regex could be

/_([0-9]+)$/ and in the match group of the result you will have 2 for 682_2 and 3 for 682_3

Ruby code snippet would be "64532_2".match(/_([0-9]+)/).captures[0]

Abhay Kumar
  • 1,467
  • 1
  • 18
  • 42
0

you can use scan which returns an array containing the matches:

string_code.scan(/(?<=_)\d/)

(?<=_) tells to find a pattern that has a given pattern (_ in this case) before itself but wont capture that, it captures only \d. if it can have more than 1 digit like 682_13,682_33 then \d+ is necessary.

buzatto
  • 6,810
  • 5
  • 14
  • 22