-2

I have to limit the data entered in the text box using the regexp for the following: Exs:

  • 1,2,3
  • 2.2,3.1,3

and if the user leaves the text box after entering 1.2,2,3. I have to remove the dot after 3 and save.

I started of restricting to enter only dot or comma with the regexp "([.,]{1})" but the text box accepts one dot whereas it allows to enter 3 commas.

jxgn
  • 741
  • 2
  • 15
  • 36
  • 2
    So, you want to allow a trailing dot with the regex? Use [`^[0-9]+[.]?[0-9]*(,[0-9]+[.]?[0-9]*)*$`](https://regex101.com/r/Lkhugb/1) – Wiktor Stribiżew Nov 23 '16 at 12:11
  • 2
    Or do you mean you only allow that dot at the end of the string only? Try `^[0-9]+([.][0-9]+)?(,[0-9]+([.][0-9]+)?)*[.]?$`, then check if the string `endsWith` the `.` and `truncate` it. – Wiktor Stribiżew Nov 23 '16 at 12:17
  • the trailing dot is nothing but if the user forgets to complete float value and stops with the dot then it has to be detected and igonred. And also i am not restricting the user to enter only 3 such values. It can be n number of values. – jxgn Nov 23 '16 at 12:44
  • Sorry, I have no clue what you need. The question sounds unclear without your code and exact real life scenario descriptions. If you need regex help, please narrow down the question. My regexps above do not restrict to only 3 values, `*` means *zero or more occurrences*. – Wiktor Stribiżew Nov 23 '16 at 12:47
  • @WiktorStribiżew with your help, i tried this (^[0-9]+[.]?[0-9]*[,]?${1,}) but it accepts only once i.e 1.2, not able to continue like 1.2,2.3 like that – jxgn Nov 23 '16 at 12:54
  • @WiktorStribiżew thanks. I didnt understand the () part now it's clear. But why {1,} this doesn't work? This also says the entire exp can happen atleast once right? – jxgn Nov 23 '16 at 13:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/128817/discussion-between-xavier-geoffrey-and-wiktor-stribizew). – jxgn Nov 23 '16 at 13:05
  • *But why {1,} this doesn't work?* - you put it after `$` and thus quantified the end of string. Nonsense - there is only 1 end of the string. – Wiktor Stribiżew Nov 23 '16 at 13:42

1 Answers1

2

For the regex itself follow the advice of Wiktor Stribiżew

Do you know QRegexValidator ? For the validation of data entered in a textbox the best way is to use a QRegexValidator

http://doc.qt.io/qt-4.8/qregexpvalidator.html#details

// regexp: optional '-' followed by between 1 and 3 digits
QRegExp rx("-?\\d{1,3}");
QValidator *validator = new QRegExpValidator(rx, this);

QLineEdit *edit = new QLineEdit(this);
edit->setValidator(validator);

Using this object the user can't enter a non valid data in the field so you don't have to process something when the user leaves the text box

baddger964
  • 1,199
  • 9
  • 18