kitz kitz - 4 months ago 15
Ruby Question

Ruby remove parts of a string

I have a problem with some regular expressions in Ruby. This is the situation:
Input text:

"NU POSTA aşa ceva pe Facebook! „Prostia se plăteşte”
Publicat la: 10.02.2015 10:20 Ultima actualizare: 10.02.2015 10:35
Adresa de e-mail la care vrei sa primesti STIREA atunci cand se intampla
Abonează-te
---- Here is some usefull text ---
Abonează-te
× Citeşte mai mult »
Adauga un comentariu"


I need a regular expression witch can extract only useful text between "Abonează-te" word.

I tried this
result = result.gsub(/^[.]{*}\nAbonează-te/, '')
to remove the text from the start of the string to the 'Abonează-te' word, but this does not work. I have no ideea how to solve this situation. Can you help me?

Answer

Instead of using regular expression, you can use String#split, then take the second part:

s = "NU POSTA aşa ceva pe Facebook! „Prostia se plăteşte”
Publicat la: 10.02.2015 10:20 Ultima actualizare: 10.02.2015 10:35
Adresa de e-mail la care vrei sa primesti STIREA atunci cand se intampla
Abonează-te
---- Here is some usefull text --- 
Abonează-te
× Citeşte mai mult »
Adauga un comentariu"
s.split('Abonează-te', 3)[1].strip  # 3: at most 3 parts
# => "---- Here is some usefull text ---"

UPDATE

If you want to get multiple matches:

s = "NU
Abonează-te
-- Here's some
Abonează-te
text --
Abonează-te
comentariu"
s.split('Abonează-te')[1..-2].map(&:strip)
# => ["-- Here's some", "text --"]