I have filenames from various digital cameras: DSC_1234.jpg,
CRW1234.jpg, etc. What I really want is the numeric portion of that
filename. How would I extract just that portion?
I expect it to involve the regex /\d+/, but I’m unclear how to extract a
portion of a string matching a regex.
I have filenames from various digital cameras: DSC_1234.jpg,
CRW1234.jpg, etc. What I really want is the numeric portion of that
filename. How would I extract just that portion?
I expect it to involve the regex /\d+/, but I’m unclear how to extract a
portion of a string matching a regex.
Thank you
This may be the simplest (and arguably the most ruby-esque):
str = “DSC_1234.jpg”
num = str.scan(/\d+/)[0]
Other ways to do it:
num = str.match(/\d+/)[0]
OR
num = (/\d+/).match(str)[0]
OR
num = str.scan(/\d+/) {|match| match}
OR
num = str =~ /(\d+)/ ? $1 : nil
That is,
num = if str =~ /(\d+)/
$1
else
nil
end
OR
if str =~ /\d+/
num = $~[0]
end
Some proponents of ruby have said that perl’s “There is more than one
way to do it,” is a curse. But the same is true of ruby. However, it
seems to me that most people learn reasonable idioms and common sense
prevails.
I have filenames from various digital cameras: DSC_1234.jpg,
CRW1234.jpg, etc. What I really want is the numeric portion of that
filename. How would I extract just that portion?
I expect it to involve the regex /\d+/, but I’m unclear how to extract a
portion of a string matching a regex.
On Tue, Jun 12, 2007 at 03:45:04PM +0900, Matt J. wrote:
I have filenames from various digital cameras: DSC_1234.jpg,
CRW1234.jpg, etc. What I really want is the numeric portion of that
filename. How would I extract just that portion?
Some solutions have been posted already, but here’s mine:
I have filenames from various digital cameras: DSC_1234.jpg,
CRW1234.jpg, etc. What I really want is the numeric portion of that
filename. How would I extract just that portion?
I expect it to involve the regex /\d+/, but I’m unclear how to
extract a
portion of a string matching a regex.