I have the following regular expression to validate blood pressure values in the form of systolic/diastolic:
\b[0-9]{1,3}\/[0-9]{1,3}\b
The expression works with the only flaw that it allows more than one non-consecutive slash (/). For example, it allows this 2/2/2
. I want it to allow only the format of a number from 1 to 999, and slash, and again a number from 1 to 999. For example, 83/23, 1/123, 999/999, 110/80, etc. Can anybody give me some help with this?
The only other expression I've found is here: ^\b(29[0-9]|2[0-9][0-9]|[01]?[0-9][0-9]?)\\/(29[0-9]|2[0-9][0-9]|[01]?[0-9][0-9]?)$
, but it doesn't work.
I have the following regular expression to validate blood pressure values in the form of systolic/diastolic:
\b[0-9]{1,3}\/[0-9]{1,3}\b
The expression works with the only flaw that it allows more than one non-consecutive slash (/). For example, it allows this 2/2/2
. I want it to allow only the format of a number from 1 to 999, and slash, and again a number from 1 to 999. For example, 83/23, 1/123, 999/999, 110/80, etc. Can anybody give me some help with this?
The only other expression I've found is here: ^\b(29[0-9]|2[0-9][0-9]|[01]?[0-9][0-9]?)\\/(29[0-9]|2[0-9][0-9]|[01]?[0-9][0-9]?)$
, but it doesn't work.
4 Answers
Reset to default 15Use ^
and $
to match the beginning and end of the string:
^\d{1,3}\/\d{1,3}$
By doing so, you force the matched strings to be exactly of that form.
Don't use the \b
word-boundaries because a slash counts as a word boundary.
The use of ^
and/or $
is likely your most simple solution. Unfortunately, if your input is a part of a string or sentence or occurs more than once in a line, etc., you've got more thinking to do.
^\b(29[0-9]|2[0-9][0-9]|[01]?[0-9][0-9]?)\/(29[0-9]|2[0-9][0-9]|[01]?[0-9][0-9]?)$
This is correct, the other had one extra \
Expanding on Blender's answer, here is a simple check for validating BP value in the format: 120/80:
if(/^\d{1,3}\/\d{1,3}$/.test(120/80)) {
console.log("BP Valid");
} else {
console.log("Invalid BP");
}
Caret(^)
andDollar($)
. – Rohit Jain Commented Feb 16, 2013 at 22:18^
and$
(unless I'm misunderstanding something, which is possible since I'm still relatively new to RegEx), there'd be no point using RegEx to match it. – David Thomas Commented Feb 16, 2013 at 22:20/
and test for array length and if valid at two, if both are between 1-999. – Jared Farrish Commented Feb 16, 2013 at 22:21