2016-05-06 3 views
0

Учитывая эту строку:соответствовать сумма цен после определенной подстроки

Looking for a front-end developer who can fix a bug on my Wordpress site. The header logo disappeared after I updated some plugins. \n\nI have tried disabling all plugins but it didn't help.Budget: $25\nPosted On: May 06, 2016 16:29 UTCCategory: Web, Mobile & Software Dev > Web DevelopmentSkills:  WordPress   Country: Denmarkclick to apply 

Я хотел бы получить значение цен после строки Budget:. У меня есть целый ряд строк с одинаковым рисунком (цена сразу после строки «Бюджет:»)

Я попробовал /\$[\d.]+/, чтобы извлечь любую сумму, но при этом любая сумма будет стоить в строке не только следующего за Budget:

Как это сделать?

+1

[ '/Budget(.*)$/'](https://regex101.com/r/wZ2gP9/1)? – Shafizadeh

+0

'str.match (/ Budget: (\ $ [\ d.] +) /) [1]'? – Dogbert

+0

Это хороший старт @ Шафизаде :). Однако мне нужно было бы зафиксировать только строку цены после «Бюджет:». В этом примере это $ 25, но это может быть $ 1000 или $ 10 000 или даже $ 100.54. – Cyzanfar

ответ

3
r =/
    \b   # match a word break 
    [Bb]  # match "B" or "b" 
    udget:  # match string 
    \s+\$  # match one or more spaces followed by a dollar sign 
    \K   # discard all matches so far 
    \d{1,3}  # match between one or three digits 
    (?:\,\d{3}) # match a comma followed by three digits in a non-capture group 
    *   # perform the preceding match zero or more times 
    (?:\.\d\d) # match a period followed by two digits in a non-capture group 
    ?   # make the preceding match optional 
    /x   # free-spacing regex definition mode 

"Some text Budget: $25\nsome more text"[r]   #=> "25" 
"Some text Budget: $25.42\nsome more text"[r]   #=> "25.24" 
"Some text Budget: $25,642,328\nsome more text"[r] #=> "25,642,328" 
"Some text Budget: $25,642,328.01\nsome more text"[r] #=> "25,642,328.01" 

Это на самом деле не совсем верно, потому что

"Some text Budget: $25,64,328.01\nsome more text"[r] #=> "25" 

должен вернуть nil. К сожалению, исправление требует серьезной операции:

r =/
    \b    # match a word break 
    [Bb]   # match "B" or "b" 
    udget:   # match string 
    \s+\$   # match 1 or more spaces followed by a dollar sign 
    \K    # discard all matches so far 
    \d{1,3}   # match between 1 and 3 digits 
    (?:    # begin a non-capture group 
     (?![\,\d]) # match a comma or digit in a negative lookahead 
     |    # or 
     (?:   # begin a non-capture group 
     (?:\,\d{3}) # match a comma followed by 3 digits in a non-capture group 
     +   # perform preceding match 1 or more times 
    )    # end non-capture group 
    )    # end non-capture group 
    (?:\.\d\d)  # match a period followed by 2 digits in a non-capture group 
    ?    # make the preceding match optional 
    /x 

"Some text Budget: $25\nsome more text"[r]   #=> "25" 
"Some text Budget: $25.42\nsome more text"[r]   #=> "25.24" 
"Some text Budget: $25,642,328\nsome more text"[r] #=> "25,642,328" 
"Some text Budget: $25,642,328.01\nsome more text"[r] #=> "25,642,328.01" 
"Some text Budget: $25,64,328.01\nsome more text"[r] #=> nil 
+0

Спасибо за ответ @Cary. Скажите, что ваше регулярное выражение захватывает этот «Бюджет:. *? (\ $ [\ D,.] +). *? $' Не исключает того факта, что 'Budget' также может быть записан как« бюджет ». Попытка понять, что является лучшим подходом (более абстрактным) – Cyzanfar

+1

Это не то, что мое регулярное выражение фиксирует то, что у вас нет, это то, что ваш захват не имеет. Например: '' Некоторые тексты Бюджет: $., .. 3 .. \ nsome more text "= ~ /.*?(\$[\d,.|+).*?$/ # => 0; $ 1 # => "$., .. 3 .." ', тогда как' 'Some text Budget: $., .. 3 .. \ nsome more text" [r] # => nil'. –

+0

oh ok Я вижу, что это отличный ответ. – Cyzanfar

1

Попробуйте это:

def extract_budget s 
    m = s.match(/Budget: \$([\d,.]+)\n/) 
    if m.nil? 
    nil 
    else 
    m.captures[0].gsub(/,/, "").to_f 
    end 
end 

Если s1 ваша строка и s2 это та же строка, но с "Бюджет: $ 25,000.53":

irb> extract_budget s1 
=> 25.0 
irb> extract_budget s2 
=> 25000.53 
irb> extract_budget "foo" 
=> nil 
+0

это не работает для подстроки типа «$ 10 000» – Cyzanfar

+0

@Cyzanfar Ознакомьтесь с обновленной версией. – nwk

+1

Конечно, это также будет соответствовать '$ ,,,,' и '$ 00..00..00', что может быть или не быть приемлемым для OP. –

1

Вы говорите, что строка «Бюджет:» не меняется, и предполагая, что нет ни одного десятичного значения, я бы использовать что-то вроде этого:

/Budget:(\s*\$\d*)/ 
+0

Это хорошо +1 спасибо – Cyzanfar

Смежные вопросы