gpt4 book ai didi

ruby - 使用正则表达式检测版本号的特定格式

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:30 24 4
gpt4 key购买 nike

我正在寻找包含版本号的数组的元素,其中版本号位于字符串的开头或结尾或由空格填充,并且是一系列数字和句点但不开头或以句号结束。例如,“10.10 Thingy”和“Thingy 10.10.5”有效,但“Whatever 4”无效。

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"]

我不确定如何修改正则表达式以要求至少有一个句点,这样“Whatever 4”就不会出现在结果中。

最佳答案

这只是 Archonic 答案的一个细微变体。

r = /
(?<=\A|\s) # match the beginning of the string or a space in a positive lookbehind
(?:\d+\.)+ # match >= 1 digits followed by a period in a non-capture group, >= 1 times
\d+ # match >= 1 digits
(?=\s|\z) # match a space or the end of the string in a 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"]

问题不是返回版本信息,而是返回具有正确版本信息的字符串。因此,不需要环顾四周:

r = /
[\A\s\] # match the beginning of the string or a space
(?:\d+\.)+ # match >= 1 digits followed by a period in a non-capture group, >= 1 times
\d+ # match >= 1 digits
[\s\z] # match a space or the end of the string in a positive lookahead
/x # free-spacing regex definition mode

haystack.select { |str| str =~ r }
#=> ["10.10 Thingy", "Thingy 10.10.5"]

假设有人想获得包含有效版本的字符串和这些字符串中包含的版本。可以这样写:

r = /
(?<=\A|\s\) # match the beginning of string or a space in a pos lookbehind
(?:\d+\.)+ # match >= 1 digits then a period in non-capture group, >= 1 times
\d+ # match >= 1 digits
(?=\s|\z) # match a space or end of string in a pos lookahead
/x # free-spacing regex definition mode

haystack.each_with_object({}) do |str,h|
version = str[r]
h[str] = version if version
end
# => {"10.10 Thingy"=>"10.10", "Thingy 10.10.5"=>"10.10.5"}

关于ruby - 使用正则表达式检测版本号的特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39112615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com