正则表达式编写求助:匹配指定术语与数字/罗马数字的短语
Hey there! Let's break down how to build this regex step by step, since you're new to regex. I'll make sure to explain each part so you understand exactly what's going on.
First, let's recap your core requirements to keep us on track:
- Case-insensitive matching (so
Class,CLASS, andclassall work) - Match sequences where one of your specified terms (
class,standard,std,grade,level,semester,sem) comes before a valid numeral (1-12 Arabic or I-XII Roman) - Allow optional space between the term and numeral
- Ignore cases where the numeral comes before the term (like your second example)
- Target the term + numeral part specifically (as in your first example where
class xiis the match)
The Final Regex
Here's the regex that meets all these needs:
(?i)\b(class|standard|std|grade|level|semester|sem)\b\s*((1[0-2]|[1-9])|(I{1,3}|IV|V|VI{1,3}|IX|X|XI|XII))\b
Step-by-Step Explanation
Let's unpack each component so you know why it's there:
(?i): This enables case-insensitive mode. You won't have to write separate patterns for uppercase, lowercase, or mixed-case versions of your terms.\b: A word boundary. This ensures we only match whole words (so we don't accidentally catch part of a longer word likeclassroomorsemesterly).(class|standard|std|grade|level|semester|sem): A grouping that matches any one of your specified terms. The|acts like an "or" operator.\s*: Matches zero or more whitespace characters. This handles optional space between the term and numeral—works for no space, single space, or even multiple spaces if they pop up.- Numeral Group:
((1[0-2]|[1-9])|(I{1,3}|IV|V|VI{1,3}|IX|X|XI|XII))(1[0-2]|[1-9]): Covers Arabic numerals 1-12.1[0-2]matches 10, 11, 12;[1-9]matches 1-9.(I{1,3}|IV|V|VI{1,3}|IX|X|XI|XII): Covers Roman numerals I-XII:I{1,3}→ I, II, III (1-3)IV→ 4;V→5;VI{1,3}→ VI, VII, VIII (6-8)IX→9;X→10;XI→11;XII→12
\b: Another word boundary to ensure the numeral is a whole word (so we don't match something likexiabcwhere the numeral is part of a longer string).
Testing It Out
- For your first example:
mathematics text book of class xi ncert→ it will match exactlyclass xi(perfect for your needs). - For your second example:
mathematics text book of viii standard ncert→ no match, since the numeralviiicomes before the termstandard(which is invalid per your rules).
Bonus Adjustment
If you want to allow optional space after the numeral plus an optional following word (but still only capture the term + numeral), you can add a non-capturing group at the end:
(?i)\b(class|standard|std|grade|level|semester|sem)\b\s*((1[0-2]|[1-9])|(I{1,3}|IV|V|VI{1,3}|IX|X|XI|XII))\b(?:\s*\w*)?
The (?:...) is a non-capturing group, so it won't store the optional space/word as a separate match—keeps your target capture clean.
Let me know if you need further clarification on any part!
内容的提问来源于stack exchange,提问作者Susmita Sadhu

