Reputation: 113
I' am using following regex:
/^(?:1|0?\.\d)$/
I need range between 0.1 and 1 with each number before and after dot. For example:
0.1 valid
1 valid
0.111 not valid
011.2 not valid
Valid numbers are [0.1-0.9] and 1
Upvotes: 0
Views: 1446
Reputation: 18611
Use
/^(?:1|0?\.[1-9])$/
See proof
Explanation
--------------------------------------------------------------------------------
^ 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
Upvotes: 1
Reputation: 6148
Bob's answer is along the right lines, however, it can do with some tweaking...
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
Alternative style
The range 0-9
can also be adjusted:
[0-9] == \d
(?<=^|[^\d\.])(0\.[1-9]|1)(?=$|[^\d\.])
Flags
You will also need to implement a couple of RegEx flags:
g : Global
m : Multiline mode
JS Example
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"]
Upvotes: 0
Reputation: 50017
The following works for the given test data:
(^|[^0-9])(0\.[1-9]|1\.0|1)($|[^0-9])
Upvotes: 1