Back to the 2026 paper

Module 1: Introduction, Lexical Analysis

20267m

For a lexical analyzer, design regular expressions to recognize the following token classes:
(i) Identifiers beginning with a letter and containing letters and digits thereafter.
(ii) Unsigned integer constants.
(iii) Relational operators <,<=,>,>=,==,<, <=, >, >=, ==, and !=!=.

Worked SolutionAI Assisted

Regular expressions for the token classes

Let

letter=[A-Za-z](often also _),digit=[0-9]\text{letter} = [A\text{-}Za\text{-}z] \quad (\text{often also } \_), \qquad \text{digit} = [0\text{-}9]

(i) Identifiers (start with a letter, then letters or digits)

id=letter (letter∣digit)∗\text{id} = \text{letter}\,(\text{letter} \mid \text{digit})^*

Accepted: total, x1, rate2023. Rejected: 2abc (starts with a digit).

(ii) Unsigned integer constants

num=digit digit∗  =  digit+\text{num} = \text{digit}\,\text{digit}^* \;=\; \text{digit}^+

Accepted: 0, 25, 1000. Rejected: -5 (sign), 3.5 (not an integer).

(iii) Relational operators

relop=  <  ∣  <=  ∣  >  ∣  >=  ∣  ==  ∣  !=\text{relop} = \; < \;\mid\; <= \;\mid\; > \;\mid\; >= \;\mid\; == \;\mid\; !=

Factored form: relop=(<∣>) (=)?  ∣  (=∣!) =\text{relop} = (< \mid >)\,(=)? \;\mid\; (= \mid !)\,=

The scanner always takes the longest match, so <= is read as one token, not < followed by =. A single = is the assignment operator, not a relational operator.

Recognizer for relop (transition diagram)

MermaidDiagram
Rendering diagram…

Final states: LT (<), GT (>), LE (<=), GE (>=), EQEQ (==), NE (!=). The states EQ1 and NOT are not final because = alone (assignment) and ! alone are not relational operators here.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.