我有一根像下面这样的绳子

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

我想删除最后一部分,以M和数字开头,这将是动态值所以结果字符串应该是
"**102-Gracecroft-Dr_Havre-de-Grace_MD**"

如何使用regex实现它。
我尝试了[/.*(?=[/d+]_M[\d-]+)/]
但它不起作用有什么想法吗?

最佳答案

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

如果星号确实是实际输入的一部分:
▶ 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**"

09-16 04:25