开发者

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 开发者_JS百科way to do this?


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

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


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

or just

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


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜