代码之家  ›  专栏  ›  技术社区  ›  yalkris

从字符串中提取带小数的第一个数字。

  •  1
  • yalkris  · 技术社区  · 6 年前

    我在regex下面有这个,我想用它从字符串中提取带小数的数字。

     scala> val numPattern = """[0-9]+.[0-9]+|[0-9]+.[0-9]+|[0-9]+""".r
     numPattern: scala.util.matching.Regex = [0-9]+.[0-9]+|[0-9]+.[0-9]+|[0-9]+
    
     scala> numPattern.findFirstIn("s2s")
     res24: Option[String] = Some(2)
    
     scala> numPattern.findFirstIn("s2.4s")
     res25: Option[String] = Some(2.4)
    

    但我想在下面的例子中提取.4和.42。

     scala> numPattern.findFirstIn("s.4s")
     res26: Option[String] = Some(4)
    
     scala> numPattern.findFirstIn("s.42s")
     res28: Option[String] = Some(42)
    

    我该怎么做?

    结果与

    scala> val numPattern="""(\d+)([.]\d+)?""".r
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Bohemian    6 年前

    试试这个正则表达式:

    \d+(\.\d*)?|\.\d+
    

    live demo .

    您可以_t同时进行两种可选的引导 尾随数字没有交替,因为它将匹配空字符串。