gpt4 book ai didi

ruby - 需要改进 ruby 正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:49 25 4
gpt4 key购买 nike

我想在字符串中查找相同模式两次。仅当与“and”连接时,但我似乎无法正确拉出第二场比赛

ruby-1.9.2-p290 :040 > text
=> "start a week and 2 days"
ruby-1.9.2-p290 :041 > text.scan /[a\d] weeks?|months?|years? and [a\d] weeks?|months?|days?/
=> ["a week", "days"]

我不明白为什么第二个匹配是“days”而不是“2 days”

如果我交换“a”和“2”,那么第二个匹配项仍然会排除该字符。

非常感谢任何帮助!


阐明我的算法将是

如果字符串包含 x 个单位和 y 个单位,则 对 x 单位做某事 对 y 单位做某事结束


我也试过

ruby-1.9.2-p290 :054 > text.scan /[a|\d] (weeks?|months?|years?) and [a|\d] (weeks?|months?|days?)/
=> [["week", "days"]]
ruby-1.9.2-p290 :055 > text.scan /([a|\d] weeks?|months?|years?) and ([a|\d] weeks?|months?|days?)/
=> []

作为实验,我尝试简化模式但没有成功改进

ruby-1.9.2-p290 :059 > text = "2 weeks and a day"
=> "2 weeks and a day"
ruby-1.9.2-p290 :060 > text.scan /[a|\d] weeks?|months?|years?|days?/
=> ["2 weeks", "day"]
ruby-1.9.2-p290 :061 > text = "a week and 2 days"
=> "a week and 2 days"
ruby-1.9.2-p290 :062 > text.scan /[a|\d] weeks?|months?|years?|days?/
=> ["a week", "days"]

感谢所有做出贡献的人...

/([a\d] years?|[a\d] months?|[a\d] weeks?) and ([a\d] days?|[a\d] weeks?|[a\d] months?)/

符合我的要求,但我绝对有兴趣知道它是否可以减小尺寸...

ruby-1.9.2-p290 :077 > text = "2 weeks and a day"
=> "2 weeks and a day"
ruby-1.9.2-p290 :078 > text.scan /([a\d] years?|[a\d] months?|[a\d] weeks?) and ([a\d] days?|[a\d] weeks?|[a\d] months?)/
=> [["2 weeks", "a day"]]
ruby-1.9.2-p290 :079 > text = "2 weeks 2 days"
=> "2 weeks 2 days"
ruby-1.9.2-p290 :080 > text.scan /([a\d] years?|[a\d] months?|[a\d] weeks?) teand ([a\d] days?|[a\d] weeks?|[a\d] months?)/
=> []

最佳答案

(a|\d) (weeks?|months?|years?) and (a|\d) (weeks?|months?|days?)

关于ruby - 需要改进 ruby 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7113596/

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