Anton Semenichenko
Anton Semenichenko

Reputation: 354

Regular expression to match a simple logic of getting the proper digits from string

Here I have a several different strings with salaries:

"U3 000 Per Month"
"U10 000 - U12 000 Per Month"
"U12 000 Per Month"
"U125 000 - U130 000 Per Month"
"U130 000 Per Month"

I'm trying to build a regex using the following logic:

Match the first 1,2 or 3 digits that come after first U letter only, then match zeros that come after a single space after first 1,2 or 3 digit group. The rest of the string doesn't matter. For example, we have few strings:

"U20 000 - U30 000 Per Month"
"U3 000 Per Month"
"U125 000 - U130 000 Per Month"

I want a regex to return

20000, 3000, 125000

Please help, I'm too exhausted of digging Regex documentation

Upvotes: 2

Views: 45

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

You could try with (?<=^U)\d{1,3}\s0*.

regex = /(?<=^U)\d{1,3}\s0*/
p 'U20 000 - U30 000 Per Month'.scan(regex).first.sub(/\s/, '') # "20000"
p 'U3 000 Per Month'.scan(regex).first.sub(/\s/, '') # "3000"
p 'U125 000 - U130 000 Per Month'.scan(regex).first.sub(/\s/, '') # "125000"

I thought in only zeros after the \s, so as you've added \d{1,3} would fit better.

Upvotes: 2

Related Questions