如何用Flex-lexer匹配C++简单赋值语句?正则匹配异常求助
Alright, let's figure out why your regex isn't matching a=2+3; and get it working correctly.
The Root Problem
Your current regex has a critical flaw in how it matches numeric literals. The pattern ([0-9][^a-zA-Z])+ is intended to match numbers, but it's actually doing two things that break the matching:
- It requires every digit to be followed by a non-letter character—so a single digit like
3can't exist on its own unless it's immediately followed by a non-letter (like;or+). - It includes those trailing non-letter characters (like
;) as part of the number match, which conflicts with the explicit";"at the end of your regex.
For example, when trying to match a=2+3;:
- The regex tries to match the final
3with([0-9][^a-zA-Z])+, which grabs3;(since;is a non-letter). - Then the regex expects an additional
;at the end (";"$), but there's no extra;left—so the match fails.
In contrast, a=2+32; works because 32 is matched as [0-9][^a-zA-Z] (the 3 is followed by 2, a non-letter), leaving the trailing ; available to satisfy the final ";" requirement.
The Corrected Regex
We need to adjust the numeric literal pattern to just match digits (without including trailing operators/semicolons) and clean up some unnecessary syntax. Here's the revised version:
stat ^[a-zA-Z][a-zA-Z0-9]*="([a-zA-Z][a-zA-Z0-9]*|[0-9]+)([+\-*/]([a-zA-Z][a-zA-Z0-9]*|[0-9]+))*;"$
Key Changes Explained
[0-9]+instead of([0-9][^a-zA-Z])+: This correctly matches any sequence of digits (single digits like3, multi-digit like23) without including trailing characters. The operators and semicolon are handled separately in the regex structure.- Simplified operator group: Replaced
("+"|"-"|"*"|"/")with[+\-*/]—character classes are cleaner and more efficient for matching single characters. - Removed possessive quantifiers: The
*+syntax is unnecessary here and can lead to unexpected behavior for simple assignment cases. Standard quantifiers (*) work perfectly.
Test Case Validation
This revised regex will correctly match all your target examples:
a=b+c;a=12;c=a+b*23;a=2+32;a=2+3;
It still enforces your core rules:
- Variable names must start with a letter, followed by any combination of letters and digits.
- Variables starting with digits are rejected.
内容的提问来源于stack exchange,提问作者Prvt_Yadav

