# Q2b · Seven regex constructions

Subject: Natural Language Processing

Exam: TEE

Reader: https://deep-learning-study-room.vercel.app/nlp/#tee/papers/legacy-f22/q2b

Canonical: https://deep-learning-study-room.vercel.app/read/nlp/tee/papers/legacy-f22--q2b/

Previous examination · complete worked answers

**Question. Define regular expressions and their uses. Write expressions for (i) all alphabetic strings, (ii) lowercase alphabetic strings ending in b, (iii) a/b strings where each a is immediately preceded and followed by b, (iv) consecutive repeated words, (v) a line starting with an integer and ending with a word, (vi) strings containing the whole words grotto and raven, (vii) capture the first English word, handling opening punctuation.** [10 marks]

### Answer

A regular expression specifies a pattern for matching text. NLP uses it for token extraction, cleaning, validation and rule-based entities. The following uses a Python/PCRE-like engine with lookaheads and backreferences; these extended features go beyond a strictly finite-state regular language.

| Task | Pattern | Why it works |
| --- | --- | --- |
| All alphabetic strings | `^[A-Za-z]+$` | Only letters; + requires at least one. Use \* if empty string is allowed. |
| Lowercase strings ending in b | `^[a-z]*b$` | The final b is mandatory. |
| a/b strings: every a surrounded by b | `^(?!a)(?!.*aa)(?!.*a$)[ab]*$` | Forbid starting a, adjacent aa, ending a. Then every a has a b on both sides. |
| Two consecutive identical words | `\b([A-Za-z]+)\s+\1\b` | Capture word, whitespace, same captured word. Case-sensitive unless ignore-case is enabled. |
| Start with integer; end with word | `^[0-9]+\b.*\b[A-Za-z]+$` | Same line; signed integers need optional [+-]. |
| Whole grotto and whole raven anywhere | `^(?=.*\bgrotto\b)(?=.*\braven\b).*$` | Two positive lookaheads require both whole words. Dot excludes newlines unless DOTALL. |
| Capture first word despite opening punctuation | `^[^A-Za-z]*([A-Za-z]+(?:[\x27’][A-Za-z]+)*)` | Group1 is first alphabetic word, with internal apostrophes allowed. |

Tests: b and bab pass rule3; a, ab, ba and baab fail. “Humbert Humbert” matches rule4; “the big bug” does not. “grottos raven” fails rule6. Regex word rules are practical ASCII conventions here, not a full linguistic tokenizer.
