简体   繁体   中英

How can I get the last occuring positive integer from a string?

I want to extract the last occurring positive integer from a string using regex. For example:

  • get-last-01-number-9.test should return 9
  • get-last-01-number7 should return 7

How can I accomplish this with regex?

You could try

(\d+)\D*$

Explanation:

(\d+) # a number
\D*   # any amount of non-numbers
$     # end of string

This will capture the number in the first capture group.

Use Negative Lookahead

Find a positive integer that isn't followed by another positive integer using a greedy match like:

/\d+(?!.*\d+)/

For example:

'get-last-01-number-9.test'.match /\d+(?!.*\d+)/
 #=> #<MatchData "9">

'get-last-01-number7'.match /\d+(?!.*\d+)/
#=> #<MatchData "7">

'get-last-01-number-202.test'.match /\d+(?!.*\d+)/
#=> #<MatchData "202">

'get-last-number'.match /\d+(?!.*\d+)/
#=> nil

This is probably slower than scanning if you have a large text blob, but some people might still find the lookahead assertion useful, especially for shorter strings.

Use Scan

A more straightforward method would be just to extract all integers (if any) with String#scan and then pop the last one. For example:

'get-last-01-number-9.test'.scan(/\d+/).pop
#=> "9"

'get-last-01-number7'.scan(/\d+/).pop
#=> "7"

'get-last-01-number-202.test'.scan(/\d+/).pop
#=> "202"

'get-last-number'.scan(/\d+/).pop
#=> nil

Scope of Answer

Negative integers weren't part of the question as originally posted, and will therefore not be addressed here. If negative integers are an issue for future visitors, and if it hasn't already been asked on Stack Overflow, please ask a separate question about them.

Use this expression to find 1+ digits with only non-digits following it till the end of the string (ie the last set of digits):

\d+(?=\D*$)

Demo

this pattern is probably the most efficient:

.*(\d+)

depending on the number of characters after the last digit to the end of string

Demo

["get-last-01-number-9.test", "get-last-01-number7"].each do |e|
    e.match(%r{\-number([\-\d]+)}) do |m|
      last_no = m[1].gsub(%r{\-}, "")
      puts "last_no:#{last_no} ---- #{File.basename __FILE__}:#{__LINE__}"
    end
end

# last_no:9 ---- ex.rb:4
# last_no:7 ---- ex.rb:4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM