rubyist rubyist - 24 days ago 7
Ruby Question

Regular expression to return modified string in ruby

I have a string like below

**102-Gracecroft-Dr_Havre-de-Grace_MD_21078_M60846-99581**


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

"**102-Gracecroft-Dr_Havre-de-Grace_MD_21078**"


How can i achieve it using regex.

Answer
▶ 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**"