-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
  • 109,145
  • 14
  • 143
  • 218
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
  • 1,351
  • 1
  • 10
  • 20
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,582
  • 1
  • 19
  • 45
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
  • 9,704
  • 5
  • 24
  • 33