You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Flex-lexer匹配C++简单赋值语句?正则匹配异常求助

Fixing Your Flex Regex for C++ Assignment Statements

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:

  1. It requires every digit to be followed by a non-letter character—so a single digit like 3 can't exist on its own unless it's immediately followed by a non-letter (like ; or +).
  2. 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 3 with ([0-9][^a-zA-Z])+, which grabs 3; (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 like 3, multi-digit like 23) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:27:59