ruby - Detect specific format of version number using regex -
i'm looking extract elements of array containing version number, version number either @ start or end of string or padded spaces, , series of digits , periods not start or end period. example "10.10 thingy" , "thingy 10.10.5" valid, "whatever 4" not.
haystack = ["10.10 thingy", "thingy 10.10.5", "whatever 4", "whatever 4.x"] haystack.select{ |i| i[/(?<=^| )(\d+)(\.\d+)*(?=$| )/] } => ["10.10 thingy", "thingy 10.10.5", "whatever 4"]
i'm not sure how modify regex require @ least 1 period "whatever 4" not in results.
this slight variant of archonic's answer.
r = / (?<=\a|\s) # match beginning of string or space in positive lookbehind (?:\d+\.)+ # match >= 1 digits followed period in non-capture group, >= 1 times \d+ # match >= 1 digits (?=\s|\z) # match space or end of string in positive lookahead /x # free-spacing regex definition mode haystack = ["10.10 thingy", "thingy 10.10.5", "whatever 4", "whatever 4.x"] haystack.select { |str| str =~ r } #=> ["10.10 thingy", "thingy 10.10.5"]
the question not return version information, to return strings have correct version information. result there no need lookarounds:
r = / [\a\s\] # match beginning of string or space (?:\d+\.)+ # match >= 1 digits followed period in non-capture group, >= 1 times \d+ # match >= 1 digits [\s\z] # match space or end of string in positive lookahead /x # free-spacing regex definition mode haystack.select { |str| str =~ r } #=> ["10.10 thingy", "thingy 10.10.5"]
suppose 1 wanted obtain both strings contain valid versions , versions contained in strings. 1 write following:
r = / (?<=\a|\s\) # match beginning of string or space in pos lookbehind (?:\d+\.)+ # match >= 1 digits period in non-capture group, >= 1 times \d+ # match >= 1 digits (?=\s|\z) # match space or end of string in pos lookahead /x # free-spacing regex definition mode haystack.each_with_object({}) |str,h| version = str[r] h[str] = version if version end # => {"10.10 thingy"=>"10.10", "thingy 10.10.5"=>"10.10.5"}
Comments
Post a Comment