-1

how to regex this string in ruby?

i have sample string like this :

a = "$65,000 /year for 2 years"
b = "Total of $120,000 ($60,000 per annum)"
c = "$40,000.0"

how to get result like this using regex :

a = "$65,000"
b = "$120,000"
c = "$40,000"

how do that?

thanks before

tardjo
  • 1,594
  • 5
  • 22
  • 38
  • why only `$120,000 ` and not `$60,000` in string `b` – aelor May 05 '14 at 05:07
  • possible duplicate of [Regex for Money](http://stackoverflow.com/questions/1028221/regex-for-money) (for the regexp part of the question) – tessi May 05 '14 at 05:17

5 Answers5

0

This will work for all prices within the range of $1,000 and $999,999:

string[/(\$\d{1,3},\d{1,3})/, 1]

This will also extract the right value (120,000) from your second string, since it always matches the first appearance in the string.

Severin
  • 8,508
  • 14
  • 68
  • 117
0

You can use scan function.

irb(main):001:0> a = "$65,000 /year for 2 years"
=> "$65,000 /year for 2 years"
irb(main):002:0> a.scan(/\$[\d,]+/)
=> ["$65,000"]
irb(main):003:0>
shantanoo
  • 3,617
  • 1
  • 24
  • 37
0

using this :

\$[^\s.]+

demo here : http://regex101.com/r/mS3eP6

and can be accomplished by using match

like this

b = "Total of $120,000 ($60,000 per annum)"
c = b.match(/\$[^\s.]+/)
c[0]

 => "$120,000"

This regex makes sure to select anything after $ and before a space or a decimal point. the match is used to capture only the first match as that is your requirement

Community
  • 1
  • 1
aelor
  • 10,892
  • 3
  • 32
  • 48
0

You can use the following regex:

\$\d{1,3}(,\d{3})*

It captures all valid numbers with a "," thousand's delimiter from $1 up.
You'll get:

a[/\$\d{1,3}(,\d{3})*/]
# => "$65,000" 
b[/\$\d{1,3}(,\d{3})*/]
# => "$120,000" 
c[/\$\d{1,3}(,\d{3})*/]
# => "$40,000" 
"Total of $12"[/\$\d{1,3}(,\d{3})*/]
# => "$12" 
"More than $12,998,109,223"[/\$\d{1,3}(,\d{3})*/]
# => "$12,998,109,223" 

You can also play with it here

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
0
a = "$65,000 /year for 2 years"
b = "Total of $120,000 ($60,000 per annum)"
c = "$40,000.0"

p a[/\$[\d,]+/] #=> "$65,000"
p b[/\$[\d,]+/] #=> "$120,000"
p c[/\$[\d,]+/] #=> "$40,000"
hirolau
  • 13,451
  • 8
  • 35
  • 47