rubyist rubyist - 1 year ago 63
Ruby Question

Regular expression to return modified string in ruby

I have a string like below


I want to remove the last part which starts with M and digits which will be dynamic values. So the result string should be like


How can i achieve it using regex.

Answer Source
▶ str = "102-Gracecroft-Dr_Havre-de-Grace_MD_21078_M60846-99581"
#⇒ "102-Gracecroft-Dr_Havre-de-Grace_MD_21078_M60846-99581"
▶ str[/.*(?=_M[\d-]+)/]
#⇒ "102-Gracecroft-Dr_Havre-de-Grace_MD_21078"

If the asterisks are indeed parts of the real input:

▶ str = "**102-Gracecroft-Dr_Havre-de-Grace_MD_21078_M60846-99581**"
▶ str.gsub /_M[\d-]+(?=\*{2}\z)/, ''
#⇒ "**102-Gracecroft-Dr_Havre-de-Grace_MD_21078**"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download