1

I have this following string:

message_id = "7bb19406-f97a-47b3-b42c-40868d2cef5b-1661496224@example.com"

I would like to extract the last part between - .* @ which is 1661496224

With forward and backward lookup, it starts from first matches of - but I want to match from last match of -:

#!/bin/ruby

message_id = "7bb19406-f97a-47b3-b42c-40868d2cef5b-1661496224@example.com"
message_id.match(/(?<=\-).*(?=\@)

output:

#<MatchData "f97a-47b3-b42c-40868d2cef5b-1661496224">

How to capture the least match (1661496224) between two characters?

Imam
  • 997
  • 7
  • 13

3 Answers3

2

Assuming that the message_id does not contain spaces, you might use:

(?<=-)[^-@\s]+(?=@)

Regex demo

If there can not be any more @ chars or hyphens after the @ till the end of the string, you can add that to the assertion.

(?<=-)[^-@\s]+(?=@[^\s@-]*$)

Regex demo

Another option with a capture group:

-([^-@\s]+)@[^-@\s]*$

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

You can match all the non-dash characters that are followed by a @:

[^-]+(?=@)

Demo: https://ideone.com/bnDxd2

blhsing
  • 91,368
  • 6
  • 71
  • 106
1

Inspired by this post on SO; what about:

s = "7bb19406-f97a-47b3-b42c-40868d2cef5b-1661496224@example.com"

puts s[/-([^-@]*)@/,1] #assuming a single '@', otherwise:
puts s.scan(/-([^-@]*)@/).last.first

Both print:

1661496224

enter image description here

JvdV
  • 70,606
  • 8
  • 39
  • 70