0

I have the following logic

def insert_type(type_list, user_input)
  case user_input
  when user_input == 'library_1'
    type_list.slice!('library_' + RegEx for any digit after library_ and stop right there + '__')
    type_list << user_input << '__'
  when user_input == 'class_A_2'
    type_list.slice!('class_' + RegEx for any digit after class_ and stop right there + _A + '__')
    type_list << user_input << '__'
  end
end

I tried to do the following

[l][i][b][r][a][r][y][_]\d{0,5} #digit from 0 to 99999

It does work, but there should be a more conventional way out there where I could start with l, and ends with the underscore, then add the number since type_list could be:

puts type_list
=> "username_John__userid_58173__userpass_8adsh20__class_A_2__library_0__"
6
  • 1
    I don't really get what you want to do. Can't you just split along __ (double underscore)? Commented Jan 12, 2014 at 7:50
  • Looks like this is what you are looking for \w+\d{0,5} Commented Jan 12, 2014 at 7:52
  • \w+\d{0,5} takes all the string though Commented Jan 12, 2014 at 7:52
  • @nhahtdh true, if I know how to take from 'l' to 'y' from 'library' I could do it up to __. :D but how do you that? Commented Jan 12, 2014 at 7:54
  • Not sure what you want to do, but if you split type_list with ruby-doc.org/core-2.1.0/String.html#method-i-split along __, you get [username_John, userid_58173, userpass_8adsh20, class_A_2, library_0]. Then for each member, you can split it again. Commented Jan 12, 2014 at 7:57

1 Answer 1

1

What you want is this:

\w+?(\d{1,5})

Or if you want a specific word, then:

library_(\d{1,5})

It will non-greedily capture the word characters, then add the numerical value to the first capture group.

Explained:

  • Any word character, including _, non greedy until we find a number
  • Any number, from 1 to 5 digits (using {0,5} here would actually be 0 to 5 digits)
  • Wrapping the digit in parentheses () allows the value to be captured.
Sign up to request clarification or add additional context in comments.

3 Comments

thank you, but what if the word that I wanted is library? Since type_list has other words inside the string and library isn't always be the first word?
If you specifically want library, then just use library_(\d{1,5})
:O Didn't know you could do that! Thank you, sir!

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.