【问题标题】:regex negative float using kohana route使用 kohana 路由的正则表达式负浮点数
【发布时间】:2014-06-14 14:16:56
【问题描述】:

我想知道为什么这个正则表达式不能在 kohana 上工作以检索浮点负数。

正则表达式:

^(-|)\d+((.|,)\d+|)$

小花路线:

Route::set('route','data/<data>',array("data"=>"^(-|)\d+((.|,)\d+|)$"));

我在regex101 上尝试了这个正则表达式,它可以工作,知道为什么它不在 kohana 路线上吗?

谢谢

【问题讨论】:

  • , 可能是 urlencoded 并且 . 不需要转义? ? 也比 (..|) imo 更具可读性
  • 您在data/&lt;data&gt; 之后忘记了结束'。此外,您可能希望删除前导 ^ 和尾随 $;我没有使用 Kohana 的经验,但我没有看到在 user guide 的任何示例中使用了这些锚。
  • 我已经添加了撇号谢谢.. 我认为 kohana 不喜欢“|”

标签: regex kohana routes


【解决方案1】:

您的正则表达式不必要地复杂并且有错误。 (.|,) 中的 . 不匹配句点,而是任何字符(正则表达式中点的含义,字符类之外)。我们要么需要转义点,如\.,要么将其包含在字符类中,如[.,]

试试这个紧凑的正则表达式:

^-\d+[.,]\d+$^-\d+([.,]\d+)?$,如果你想让小数部分可选。

您原来的正则表达式建议您允许逗号。如果没有,请使用:

^-\d+\.\d+$^-\d+(\.\d+)?$,如果你想让小数部分可选。

解释正则表达式

^                        # the beginning of the string
-                        # '-'
\d+                      # digits (0-9) (1 or more times (matching
                         # the most amount possible))
[.,]                     # any character of: '.', ','
\d+                      # digits (0-9) (1 or more times (matching
                         # the most amount possible))
$                        # before an optional \n, and the end of the
                         # string

【讨论】:

  • 感谢您的回答,我通过使用 "(-)?\d+((\.)\d+)?" 解决了这个问题
  • 感谢您提供所有这些非常有用的详细信息,我会将您的问题标记为好问题 =)
  • @zeomega 谢谢,下次见。 :)
猜你喜欢
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多