简体   繁体   中英

How to match last occurrence in a string with Regex

Hi I am working on RoR project with ruby-2.5.0 and Rails 5. I have a pattern to find time from a string as follows:-

time_pattern = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/
time = mystr[time_pattern]

It retuns the first matching time in the string for example if there are two times are present in the string "14:04" and "14:05" it will always return the first one which is "14:04". i need to find the second one. Please help me to find the second match using regex. I have also tried the scan method like:-

time = params.to_s.scan(time_pattern).uniq.flatten.last

But my rubocop throws an error Methods exceeded maximum allowed ABC complexity (1) Please help. Thanks in advance.

Try using the following expression: /(\\d{2}:\\d{2}(:\\d{2})?)/g .

Here is an example of it running in ruby :

re = /(\d{2}:\d{2}(:\d{2})?)/
str = ' "14:04" and "14:05"'

# Get matches
matches = str.scan(re)

# Get last match
matches = str.scan(re)

# Get last match
lastMatch = str.scan(re).last[0]

# Print last match
puts lastMatch.to_s
# OUTPUT => "14:05"

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

Last Regex Match

To get the last match you can simply call #last on the #scan result.

regex = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/ # original
# or
regex = /\d{2}(?::\d{2}){1,2}/ # kudos @ctwheels

string = '12:01, 12:02, 12:03:04, 12:05'

string.scan(regex).last
#=> "12:05"

ABC-Metric

The ABC Metric is more complex and would require having a look at your whole method. But here is a blog post that explains it pretty well: Understanding Assignment Branch Condition

Another options is to change the max ABC size in the RuboCop settings. Have a look at the RuboCop Configuration Documentation and the default configuration (Metrics/AbcSize max size is set to 15 by default).

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