line edit validator number regex
-
i need to have validator on my line edit.
the format of the acceptable input is as following: list of<number>
s, or list of<number-number>
s, or list of both, e.g.4-8 10 34-100 222
i have compiled the following regexp:([1-9]\d*(-[1-9]\d*)?\s*)+
but it falsely allows5-55-55-55-555
, while i need just5-55
and not allow hyphen after second number
what's the correct regex to use? -
Hi,
You are over-engineering it:
R"^(\d+|\d+-\d+)$"
Should do it
-
@user4592357
@SGaist's pattern does not allow negative numbers. For a space-separated list, you could go for, say:R"^((\d+|\d+-\d+) *)+$"
There are other ways, depending on whether you need captures.
-
@user4592357
So replace each\d
token with something like([1-9]\d*)
.If you want to start putting more constraints on, like say in the
\d+-\d+
case you might want the right hand number to be greater than the the left hand one, it's time to pull out the matches and do some numeric comparisons in a more advanced validation. -
@user4592357
You want me to test it for you?! Start using an on-line resource to design & test the reg exs you want to use, e.g. https://regex101.com/ . -
You also have the regular expression tool that you can build and will give you the exact string you need in your code.
-
@user4592357 said in line edit validator number regex:
unfortunately,
^((\d+|\d+-\d+) *)+$
regex still allows hyphen after5-555
.Pardon?
5-555-
gives Your regular expression does not match the subject string..Instead of making us guess what input you have in mind, could you please test with one of the reg ex validators we referenced and paste precisely what string you claim it does/does not match?
-
hi
@JonB said in line edit validator number regex:5-555- gives Your regular expression does not match the subject string..
If you write another number after the "5-555-" , then it will be accepted, ex : 5-555-8
OP only wants to accept groupes of 2 numbers separated by a hyphen. -
-
anyways, i wanna understand why the regex with
\b
allows55-555-
? how does it match/validate?Neither of the two regexs I have given with
\b
allow55-555-
. As tested at rex101.com.I am finding your questions/statements very hard to comprehend....
-
@user4592357
So when you saidwhy the regex with
\b
allowsyou meant
why the regex without
\b
allows! :)
Regex:
^((\d+|\d+-\d+) *)+$
Input:5-555-8
You want to know why the input does match here. That's because in order to force a match if it possibly can, which is how reg exs work, this gets treated as though it were:
5-55 5-8
i.e. two separatedigits-digits
sequences. So I put in the\b
word-boundary token in^((\d+|\d+-\d+)\b *)+$
to prevent it splitting in the middle of a sequence of consecutive digits.