非零负十进制数的正则表达式

时间:2017-08-09 14:32:48

标签: javascript regex

我使用^-\d*\.?\d+$进行负数匹配。但这接受-0。 我想限制正则表达式匹配-0。有人可以帮忙吗? 提前致谢。

2 个答案:

答案 0 :(得分:4)

您可以使用

^-(?!0*\.?0+$)\d*\.?\d+$
  ^^^^^^^^^^^^

请参阅regex demo

如果字符串只包含(?!0*\.?0+$),那么-否定前瞻将使匹配失败,然后是一个表示零的int / float数字。

<强>详情:

  • ^ - 字符串开头
  • - - 连字符
  • (?!0*\.?0+$) - 在当前位置之后,如果匹配以下模式,则匹配失败:
    • 0* - 零个或多个0 s
    • \.? - 可选的.
    • 0+ - 1个或多个0 s
    • $ - 字符串结尾
  • \d* - 0+位数
  • \.? - 可选的.
  • \d+ - 一位或多位
  • $ - 字符串结束。

答案 1 :(得分:2)

也许正则表达式不是正确的工具。

library(vegan)
library(ggplot2)

cols = c("blue","red")
cols1 = c("green","dark orange")
cols2 = c("purple","yellow")

data(dune)
sites = data.frame(year = rep(c(1:5), times= 4), dune = rep(c(1:4),each=5), dune.type = rep(c("A","B"),each=10))
distances <- vegdist(dune, method = "bray")

#create Betadispersion model on betad (effectively a PCoA)
mod1 <- with(sites, betadisper(distances, dune, type = "centroid"))
s = scores(mod1)

# Get points
pnt_sites = as.data.frame(s$sites)
pnt_sites = cbind(pnt_sites, sites)

# Get centroids
pnt_centroids = as.data.frame(s$centroids)
pnt_centroids$dune = rownames(pnt_centroids)
pnt_centroids$dune.type = rep(c("A","B"),each=2)

# Calculate segments
seg = pnt_sites[, c("PCoA1", "PCoA2", "dune")]
tmp = rename(pnt_centroids, c("PCoA1" = "PCoA1_ctr", "PCoA2" = "PCoA2_ctr"))
seg = join(seg, tmp, "dune")

# Plot
ggplot() +
  geom_point(
    data = pnt_sites,
    aes(x = PCoA1, y = PCoA2, colour = dune.type, shape = dune.type),
    size = 2
  ) +
  geom_segment(
    data = seg,
    aes(x = PCoA1, y = PCoA2, xend = PCoA1_ctr, yend = PCoA2_ctr, colour = 
       dune.type)
  ) +
  geom_point(
    data = pnt_centroids,
    aes(x = PCoA1, y = PCoA2, fill = dune.type),
    size = 3, shape = 21
  ) +
  scale_colour_manual(values=cols, guide= FALSE) +
  coord_equal() +
  theme_bw()