英文:
Regex with range negative value to positive
问题
你好,我需要创建一个正则表达式,用于匹配范围在-1到1之间的数字。聊天中遇到了问题,而且我也没有找到很多答案。
现在我遇到了困难,因为我的正则表达式还匹配了-1.5和1.5的值,但它不应该这样。我的当前正则表达式是: ^-?1(\.0+)?|^-?0(\.[0]+)?$。
英文:
Hi I need to create regex that will match numbers in range -1 to 1, chat got problem with that and also i didn't find many answers.
Now I'm stuck because my regex match also -1.5 and 1.5 value but it shouldn't, my current regex is: ^-?1(\.0+)?|^-?0(\.[0]+)?$
答案1
得分: 1
^-?1(\.0+)?|^-?0(\.[0-9]+)?$
解释:
-
^表示字符串的开头。 -
-?匹配可选的减号。
1(\.0+)?匹配数字1,后面可以有可选的小数点和一个或多个零。 -
|是交替操作符,允许匹配先前的模式或下一个模式。 -
^-?0(\.[0-9]+)?$匹配数字0或-1到1之间的小数。
使用此正则表达式匹配的示例数字:
-1
-0.5
0
0.5
1
不匹配的示例数字:
-1.5
1.5
-2
2
英文:
Try this: ^-?1(\.0+)?|^-?0(\.[0-9]+)?$
Explanation:
-
^asserts the start of the string. -
-?matches an optional minus sign.
1(\.0+)?matches the number 1 followed by an optional decimal point and one or more zeros. -
|is the alternation operator, allowing matching either the previous pattern or the next pattern. -
^-?0(\.[0-9]+)?$matches the number 0 or a decimal number between -1 and 1.
Examples of matching numbers using this regex:
-1
-0.5
0
0.5
1
Examples of non-matching numbers:
-1.5
1.5
-2
2
答案2
得分: 1
第一个模式中缺少锚点 $。
要匹配所有中间的值,您可以匹配要么是1后跟.和1个或多个零,要么是可选的零后跟.和1个或多个数字:
^-?(?:1(?:\.0+)?|0+(?:\.\d+)?)$
解释
^字符串的开头-?匹配可选的-(?:用于替代的非捕获组1(?:\.0+)?匹配1,可选地匹配.和1个或多个零|或0+(?:\.\d+)?匹配0,后跟可选的部分匹配.和1个或多个数字
)关闭非捕获组$字符串的结尾
英文:
The first alternative in your pattern is missing the anchor $
To match all the values in between, you can match either 1 followed by . and 1+ zeroes, or match optional zeroes followed by . and 1+ digits:
^-?(?:1(?:\.0+)?|0+(?:\.\d+)?)$
Explanation
^Start of string-?Match optional-(?:Non capture group for the alternatives1(?:\.0+)?Match 1 with an optional part matching.and 1+ zeroes|Or0+(?:\.\d+)?Match 1 with an optional part matching.and 1+ digits
)Close the non capture group$End of string
答案3
得分: 0
如果数字是正确格式的小数,你只需要使用
^-?(0|1|0\.\d+)$
然而,如果它们不是...
忽略^$的边界和始终相同的可选-?,你需要:
1(\.0*)?- 用于解析1,1.,1.00?\.\d+- 用于解析0.123,.1230\.\d*- 用于解析0,0.,0.123\d+(\.\d*)?[eE]-\d+- 用于解析1e-12,1E-12,1.e-12,1.23e-12
(以上在Javascript中都是有效的数字)
最终得到 ^-?(1(\.0*)?|0?\.\d+|0\.\d*|\d+(\.\d*)?[eE]-\d+)$
(仍然缺少0.123e1,12.3e-1和1e0的变体)
英文:
If the numbers are properly formatted decimals, all you need is
^-?(0|1|0\.\d+)$
However, if they are not...
Ignoring ^$ bounds and optional -? which are always the same, you need:
1(\.0*)?- to parse1,1.,1.00?\.\d+- to parse0.123,.1230\.\d*- ro parse0,0.,0.123\d+(\.\d*)?[eE]-\d+- to parse1e-12,1E-12,1.e-12,1.23e-12
(all are valid numbers at least in Javascript)
resulting in ^-?(1(\.0*)?|0?\.\d+|0\.\d*|\d+(\.\d*)?[eE]-\d+)$
(and it's still missing 0.123e1, 12.3e-1 and 1e0 variants)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论