AMACB
AMACB

Reputation: 1298

Find the first index of a non-numeric character

Suppose I have a String:

someString = "1374j03d42s23dc"

I want to find the first index of a non-numeric character. In this case, that would be 4. How can I do this with a regex?

(I'm not very good at regex, so it would be great if the answer could explain what is going on)

Upvotes: 0

Views: 5329

Answers (3)

spickermann
spickermann

Reputation: 106802

In addition to sawa's solution: You could also use String#index when you like your code to be more readable:

string = '1374j03d42s23dc'
string.index(/\D/)
#=> 4

/\D/ matches any non-digit (list of common regexp metacharacters)

Upvotes: 3

Sagar Pandya
Sagar Pandya

Reputation: 9497

Try:

someString.each_char.with_index { |c,i| puts i if c == someString.scan(/\D+/)[0] }

Upvotes: 0

sawa
sawa

Reputation: 168091

someString =~ /\D/
# => 4

........

Upvotes: 4

Related Questions