0

I need to extract a string 'MT/23232' I have written the below code, but it's not working, Can any one help me here?

'Policy created with MT/1212'
'Policy created with MT/121212'
'Policy created with MT/21212121212'

I have written this code

msg="MT/33235" id = msg.scan(/MT/\d+/\d+/)[0]

But it's not working for me, Can any one help me to extract this string?

2 Answers 2

1

You need to escape the forward slash which exists next to MT in your regex and you don't need to have a forward slash after \d+ . And also i suggest you to add a lookbehind, so that you get a clean result. (?<=\s) Positive lookbehind which asserts that the match must be preceded by a space character.

msg.scan(/(?<=\s)MT\/\d+/)[0]

If you don't care about the preceding character then the below regex would be fine.

msg.scan(/MT\/\d+/)[0]

Example:

> msg = 'Policy created with MT/21212121212'
=> "Policy created with MT/21212121212"
> msg.scan(/(?<=\s)MT\/\d+/)[0]
=> "MT/21212121212"
> msg.match(/(?<=\s)MT\/\d+/)[0]
=> "MT/21212121212"
Sign up to request clarification or add additional context in comments.

11 Comments

hi Avinash thanks, but why are you using scan, you could have used STring#[], right?
to do a single match, match function would be enough.
Yes, But what I am saying is, you could have written the code like puts msg[/MT\/\d+/] rather than scan function,Isn't it? because it always returns the first value.
i don't know how scan func returns only the first value. scan is used to do a global match.
sorry, I meant to say scan()[0]
|
1
your_string.scan(/\sMT.*$/).last.strip

If your required substring can be anywhere in the string, then:

your_string.scan(/\bMT\/\d+\b/).last.strip # "\b" is for word boundaries

Or you can specify the acceptable digits this way:

your_string.scan(/\bMT\/[0-9]+\b/).last.strip

Lastly, if the string format is going to remain as you specified, then:

your_string.split.last

5 Comments

Mark the answer as selected if it answers your question.
I don't understand what you are saying, is there any button named 'selected' which I need to click?
"your_string.split('Policy created with ').last" I can't use this one, because that string may appear at any place, it may appear in the middle as well.
You haven't answered the question: why the OP's code doesn't work.
I think I have. The OP asked Can any one help me to extract this string?. Also, I'm sure that after looking at my response, the OP has learned what was wrong in his regex.

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.