重复正则表达式匹配数学符号然后编号失败

时间:2016-02-01 15:20:34

标签: ruby regex

我正在尝试将1+21*2/3....等mathematica表达式与无穷大相匹配。有人可以解释为什么我的正则表达式匹配下面的最后一个案例,以及如何修复它以便它只匹配有效的表达式(可能永远延伸)?

perms=["12+2*4","2+2","-2+","12+34-"]
perms.each do |line|
    puts "#{line}=#{eval(line)}" if line =~ /^\d+([+-\/*]\d+){1,}/
end

我希望输出为:

12+2*4=20
2+2=4

2 个答案:

答案 0 :(得分:6)

> dput(droplevels(head(df))) structure(list(SOX2 = c("4-acetylantroquinonol B", "arsenite", "Estradiol", "bisphenol A", "butyraldehyde", "C646 compound"), EGR1 = c("1,10-phenanthroline", "1-nitropyrene", "2,2,4,4-tetrabromodiphenyl ether", "2-(2-amino-3-methoxyphenyl)-4H-1-benzopyran-4-one", "22-hydroxycholesterol", "2-amino-1-methyl-6-phenylimidazo(4,5-b)pyridine"), FOS = c("1-nitropyrene", "2-(2-(4-(4-nitrobenzyloxy)phenyl)ethyl)isothiourea methanesulfonate", "2-(2-amino-3-methoxyphenyl)-4H-1-benzopyran-4-one", "22-hydroxycholesterol", "2,4-dinitrotoluene", "2-amino-1-methyl-6-phenylimidazo(4,5-b)pyridine" ), RUNX2 = c("2-(2-amino-3-methoxyphenyl)-4H-1-benzopyran-4-one", "Acetylcysteine", "arsenic trioxide", "Ascorbic Acid", "7,8-Dihydro-7,8-dihydroxybenzo(a)pyrene 9,10-oxide", "Estradiol")), .Names = c("SOX2", "EGR1", "FOS", "RUNX2"), row.names = c(NA, 6L), class = "data.frame") 内,[character set]字符定义范围字符 - 考虑-[a-z]。如果您想匹配文字[0-9],则必须是第一个或最后一个字符。

-

其他事项:/^\d+(?:[+\/*-]\d+)+$/ 正是{1,};你也需要在最后锚定,所以你不能匹配+

答案 1 :(得分:0)

您应该使用$完成表达式以匹配整个输入字符串:

/^\d+([-+\/*]\d+){1,}$/

连字符-的错误位置是表达式中的一个错误来源。缺少$另一个。