Reputation: 898
I have the following string
Policy 023203232/02/05 saved successfully
And I need to extract 023203232/02/05
from the above string and I have written the following code
puts a[/\d+\/\d+\/\d+/]
And it works fine. But If the number increases with the slashes like, 023203232/02/05/06
I have to include one more \d+
but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution
If string is
Policy 023203232/02/05 saved successfully
Then
023203232/02/05
If string is
Policy 023203232/02/05/06 saved successfully
Then
023203232/02/05/06
If string is
Policy 023203232/02/05/06/08 saved successfully
Then
023203232/02/05/06/08
How to write such a generic regular expression?
Upvotes: 0
Views: 65
Reputation: 54223
This regex should be what you're looking for :
/(\d+\/?)+/
It means :
/
It should be a bit more robust than the other answers :
"Policy 023203232/02/05/06/08 saved successfully"[/(\d+\/?)+/]
# => "023203232/02/05/06/08"
"Policy 023203232/02/05/07/3434343/56 saved successfully 09/56/32"[/(\d+\/?)+/]
# => "023203232/02/05/07/3434343/56"
"Policy // // 023203232/02/05/07/3434343/56 saved successfully 09/56/32"[/(\d+\/?)+/]
# => "023203232/02/05/07/3434343/56"
If you want to make sure that the number is right after 'Policy ' but don't want to have 'Policy '
inside your match, you can use a positive look-behind :
/(?<=Policy )(\d+\/?)+/
Here in action :
"2017/03/31 Policy 023203232/02/05/07/3434343/56 saved successfully"[/(?<=Policy )(\d+\/?)+/]
# => "023203232/02/05/07/3434343/56"
Upvotes: 1
Reputation: 80065
This one looks for a serie of digits or slashes:
str = "Policy 023203232/02/05/07/3434343/56 saved successfully 09/56/3"
p str.match(/[0-9\/]+/)[0] # => "023203232/02/05/07/3434343/56"
Upvotes: 1
Reputation: 5690
Assuming contiguous digits and slashes (i.e. no spaces in between), this should work:
a.scan(/\d+\/?/).join
Upvotes: 2