I’m attempting to create a valid regular expression to detect if a string is only numbers and digits or if it contains letters.
The expression I’m using is:
/^d+.?d+$|^d+$/.test(masked)
However whenever I type the next (.) index, the expression turns false:
const masked = '123.422' -> TRUE
const masked = '123.422.' -> FALSE (SUPPOSE TO BER TRUE)
What I want to achieve is:
const masked = '123.422.433-43' -> TRUE
const masked = 'Hello' -> False
2
Answers
Try
It will match if there are no letters
Your description is insufficient, but I’ll try to give it a try anyway since I enjoy creating regex.
from your description, I assume you know very little about regex, and if you need some help how to use it, you should take a look at this online tool called Regexr
The Regex you are using, (that I simplified removing the beginning and end characters)
d+.?d+|d+.
only accepts these formats:DIGIT(S) + DIGIT(S) ( left side expr when dot is missing)
DIGIT(S) + DOT + DIGIT(S) ( left side expr with dot )
DIGIT(S) + DOT
this means it fails on a simple case, with the current format, you can’t have a single digit.
This is my suggestion:
The expression might start with a dot, followed by a sequence of Digits and dots.
This allows numbers like
123
,.123
,123.123
or.123..123.
You can’t have more than one consecutive dots. or just a single dot.