gpt4 book ai didi

正则表达式匹配 1+ 字符,但不是 500 字符

转载 作者:行者123 更新时间:2023-12-04 02:53:51 32 4
gpt4 key购买 nike

我正在寻找一个正则表达式,它可以匹配长度为 1 个或多个字符但匹配 500 的内容。这将在 Rails 路由文件中使用,特别是用于处理异常。

路线.rb

match '/500', to: 'errors#server_error'
match '/:anything', :to => "errors#not_found", :constraints => { :anything => /THE REGEX GOES HERE/ }

我对如何定义匹配某些内容但同时不匹配其他内容的正则表达式有点迷茫。

最佳答案

您可以使用此正则表达式检查字符串是否不包含子字符串 500:

\A(?>[^5]++|5++(?!00))+\z

如果你想允许 5000 或 5500...,你可以这样做:

\A(?>[^5]++|5{2,}+|5(?!00(?!0)))+\z

第一个字符串解释:

\A           # begining of the string
(?> # opening of an atomic group
[^5]++ # all characters but 5 one or more times (possessive)
| # OR
5++(?!00) # one or more 5 not followed by 00
)+ # closing of the atomic group, one or more times
\z # end of the string

Possessive quantifiersatomic groups在这里是为了避免正则表达式引擎回溯以获得更好的性能(正则表达式很快就会失败)。

关于正则表达式匹配 1+ 字符,但不是 500 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088913/

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