Blankman
Blankman

Reputation: 266978

How to get all leading characters before the first instance of a number

I have product codes that look like:

abc123
abcd23423

I need to get all the leading characters before the first instance of a number, so:

abc
abcd

What's the best way to do this?

Upvotes: 0

Views: 250

Answers (4)

Aaa
Aaa

Reputation: 1854

You can use a regular expression which detects the beginning of the string (\A) and tries to capture as many non-digit characters (\D*) as possible (* is greedy by default):

processed_codes = codes.map { |code| code.scan(/\A(\D*)/)[0] }

You can also use String#match of course, but it has less predictable/intuitive behavior.

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160551

DATA.each do |l|
  chars = l[/^([[:alpha:]]+)/, 1] # [:alpha:] = [a-zA-Z]
  puts chars
end

__END__
abc123
abcd23423

# >> abc
# >> abcd

If you want to capture the alpha into an array do something like this:

ary = []
DATA.each do |l|
  ary << l[/^([[:alpha:]]+)/, 1] # [:alpha:] = [a-zA-Z]
end
ary # => ["abc", "abcd"]

__END__
abc123
abcd23423

I didn't use \D because it means all non-numeric (AKA [^0-9]), but that can be dangerous if you are going to run into any other text that is not an alpha character:

'abc_-$%#123'[/^(\D+)/, 1] # => "abc_-$%#"

For the same reason \w is not necessarily safe:

'abc_-$%#123'[/^(\w+)/, 1] # => "abc_"

[[:alpha:]] is the alphabet characters [a-zA-Z]

'abc_-$%#123'[/^([a-zA-Z]+)/, 1] # => "abc"
'abc_-$%#123'[/^([[:alpha:]]+)/, 1] # => "abc"

Upvotes: 0

steenslag
steenslag

Reputation: 80065

'abc123 abcd23423'.split(/\d+/).join

or just

'abc123 abcd23423'.gsub(/\d+/,'')

Upvotes: 0

nonopolarity
nonopolarity

Reputation: 150986

 "abc123 abcd23423".scan(/(\D*)\d+/)
  => [["abc"], [" abcd"]]

 "abc123 abcd23423".scan(/(\D*)\d+/).join
  => "abc abcd"

Upvotes: 2

Related Questions