Time for action – a simple quiz game
To introduce you to the main usage of QRegularExpression
, let's imagine this game: a photo, showing an object, is shown to multiple players and each of them has to estimate the object's weight. The player whose estimate is closest to the actual weight wins. The estimates will be submitted via QLineEdit
. Since you can write anything in a line edit, we have to make sure that the content is valid.
So what does valid mean? In this example, we define that a value between 1 g and 999 kg is valid. Knowing this specification, we can construct a regular expression that will verify the format. The first part of the text is a number, which can be between 1 and 999. Thus, the corresponding pattern looks like [1-9][0-9]{0,2}
, where [1-9]
allows—and demands—exactly one digit, except zero, which is optionally followed by up to two digits including zero. This is expressed through [0-9]{0,2}
. The last part of the input is the weight's unit. With a pattern such as (mg|g...