我正在使用以下正则表达式:
/^(?:1|0?\.\d)$/
我需要在0.1和1之间的范围内,每个数字在点之前和之后。例如:
0.1 valid
1 valid
0.111 not valid
011.2 not valid
有效数字为[0.1-0.9]和1
答案 0 :(得分:2)
使用
/^(?:1|0?\.[1-9])$/
请参见proof
说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
0? '0' (optional (matching the most amount
possible))
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
[1-9] any character of: '1' to '9'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
答案 1 :(得分:1)
答案 2 :(得分:0)
鲍勃的答案是正确的,但是,可以做一些调整...
1. | .1
不匹配\n
RegEx
(?<=^|[^[0-9]\.])(0\.[1-9]|1)(?=$|[^[0-9]\.])
(?<= : Start of positive look behind
^ : Matches start of string
| : OR operator
[^0-9\.] : Matches anything but 0-9 or literal "."
) : End of look behind group
( : Start of capture group
0\.[1-9] : Matches 0.1 -> 0.9
| : OR operator
1 : Matches 1 on it's own
) : End of capture group
(?= : Start of positive look ahead
$ : Matches end of string
| : OR operator
[^0-9\.] : Matches anything BUT 0-9 or literal "."
) : End of look ahead
替代样式
还可以调整范围0-9
:
[0-9] == \d
(?<=^|[^\d\.])(0\.[1-9]|1)(?=$|[^\d\.])
标志
您还需要实现几个RegEx标志:
g : Global
m : Multiline mode
JS示例
var data = `
0.1 : Match
1 : Match
0.111 : No-match
011.2 : No-match
1.2 : No-match
0.2 : Match
0 : No-match
0.1 : Match
.1 : No-match
1.0 : Match
`;
var re = /(?<=^|[^\d\.])(0\.[1-9]|1)(?=$|[^\d\.])/gm;
console.log(data.match(re)); // Output: ["0.1", "1", "0.2", "0.1"]