Kim
Kim

Reputation: 2156

extract substring in string

I have the following string:

expression_patterns_attributes_2_location_attributes_PTN_PATTERN

I need to extract only the number after 'expression_patterns_attributes_'

I did the following:

<%= string_a = "expression_patterns_attributes_2_location_attributes_PTN_PATTERN"
<% z_index1 = string_a.slice! "expression_patterns_attributes_" %>
<% z_index2 = string_a.slice! "_location_attributes_PTN_PATTERN"     %>
<%= string_a %> yields '2'

Is there a neater way of extracting the number from the string?

Thanks for your suggestion

Upvotes: 0

Views: 100

Answers (2)

Mori
Mori

Reputation: 27779

s = 'expression_patterns_attributes_2_location_attributes_PTN_PATTERN'
s[/\d+/] # => "2"

Upvotes: 2

Anthony Alberto
Anthony Alberto

Reputation: 10395

If you're sure that string_a is always well formed :

string_a.split("_")[3]

Upvotes: 1

Related Questions