I’m trying to write a regular expression that will validate a variable assignments in a BB style code that I’m currently developing.
Variable assignments look like this
[assign {var_name} = "string value"]
You can assign to multiple variables like
[assign {var1} = {var2} = true]
Or add to a variable with
[assign {var_name} .= " more..."]
Increment/decrement variables
[assign {var}++] or [assign {var}--]
Assign a negated value
[assign {var1} = !{var2}]
So far I’ve come up with the following regex with doesn’t work very well
/
\[assign
(?:
[\s]*(?:
[\!]?\{[^\}]+\}(?:(?:\+\+)|(?:\-\-))?
|
[0-9]+
|
\"[^\"]+\"
|
\'[^\']+\'
|
true
|
false
)[\s]*(?:\=[\s]*|\.\=[\s]*)?
)+
\]
/
I’m stuck with the following:
- I need to ensure that .= or = is used between each part
- And ensure that values and variables are assigned to variables, but not variables assigned to values
- Finally ensure there is an actual assignment unless the value is incremented or decremented
Update:
working regex
\[assign(?:\s)*
(
\{[^\}]+\}
(?:
\+\+
|
--
|
(?:\s)*(?:\.)?=(?:\s)*
(?:(?:!)?\{[^\}]+\}(?:\s)*(?:\.)?=(?:\s)*)*
(?:
[0-9]+
|
"[^"]+"
|
'[^']+'
|
true
|
false
|
(?:!)?\{[^\}]+\}
)
)
)
(?:\s)*\]
If you only need to match those cases, you could use the following regular expression to parse them:
It will match the following:
And it will not match the following: