Skip to content Skip to sidebar Skip to footer

Using Regex To Pass Syntax-valid C++ Declaration/initialization (considering Their Data Types)

This question is related to this: Using regex to pass syntax-valid c++ declaration/initialization thanks to the answer of Jerry. But now the program flow has been redesigned. It w

Solution 1:

For the integer one, you could perhaps use this:

^(?:[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+)?,\s*)*[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+)?;$

These will match a,b;, a=0,b=333; and reject a, b=; or a='sts' or b=false, c=23.0.

For the float, maybe that one:

^(?:[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+(?:\.[0-9]+)?)?,\s*)*[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+(?:\.[0-9]+)?)?;$

For the character syntax, I guess:

^(?:[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*'[^']')?,\s*)*[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*'[^']')?;$

And for the boolean one, maybe that:

^(?:[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*(?:true|false))?,\s*)*[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*(?:true|false))?;$

Note: Those were specifically made for the examples you provided. I cannot guarantee that it will work for all the different scenarios you have since I don't have much experience with C++.

EDIT: Adding operators to float and integer regexes:

int

^(?:[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+(?:[+\/*-][0-9]+)?)?,\s*)*[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+(?:[+\/*-][0-9]+)?)?;$

float

^(?:[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+(?:\.[0-9]+)?(?:\s*[+\/*-[0-9]+(?:\.[0-9]+)?)?)?,\s*)*[A-Za-z_][A-Za-z0-9]*\s*(?:=\s*[0-9]+(?:\.[0-9]+)?(?:\s*[+\/*-[0-9]+(?:\.[0-9]+)?)?)?;$

Post a Comment for "Using Regex To Pass Syntax-valid C++ Declaration/initialization (considering Their Data Types)"