1

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

How can i achieve it using regex. i tried with [/.*(?=[/d+]_M[\d-]+)/]

But it is not working. Any ideas?

1
  • The removed "last part" actually starts with _M and the "dynamic values" contains a - in addition to digits. Commented Nov 15, 2016 at 11:38

1 Answer 1

4
▶ 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**"
Sign up to request clarification or add additional context in comments.

7 Comments

I want to exclude 21078 also. Sorry. I typed the resultant string wrongly. It should be "102-Gracecroft-Dr_Havre-de-Grace_MD"
This is easily achievable basing on snippet I have provided. Left as a homework.
I tried with the below one. .*(?=[/d+]_M[\d-]+) But it dint work either. Any suggestions
You have a typo (forward slash instead of back slash, and there is underscore to take into account, and + should not be disclosed within square brackets...) It should be .*(?=_\d+_M[\d-]+).
@ mudasobwa. But this returned me 102-Gracecroft-Dr_Havre-de-Grace_MD_2107. excluding only '8'. I want to exclude 21078 also.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.