-1

There's no better way of explaining than with an example: say I have a for loop:

for(int i = 0; i<n;i++){

I basically want a regex that groups i = 0, i<n, and i++ into three separate groups.

so far, i have this:

for\s*\(\s*[^\w\s]?(\w+=\d+)\s*;\s*([^;]+)\s*;\s*([^)]+)\s*\)\s*({)?

and it gives me the i<n and the i++ but due to the type specifier on the first part, it does not give me i = 0 and I'm not sure how to do it.

I also need to account for when there are no type specifiers at all. I basically want to skip the first word if there are two words before the =. Is this a possible regular expression?

2
  • 2
    You can't parse C++ using simple regular expressions. Each clause in the for loop could be too complex for a regular expression. Just the initial "definition" clause is too complex for regular expressions. What is the actual problem you try to solve? What is your exercise or assignment? Commented Sep 15, 2024 at 10:25
  • Please edit your question to include several example input strings you can have. Also describe the limitations of the possible for loop headers you can have. Commented Sep 15, 2024 at 10:43

1 Answer 1

0

This regex:

for\s*\(\s*(?:\w+\s+)?(.+?\s*=\s*.+?)\s*;\s*(.+?);\s*(.+?)\s*\)

has match groups i = 0, i<n, and i++ in both these cases:

for(int i = 0; i<n;i++){
for (i = 0;i<n;i++) {

This is an ok tool if you're testing against a fixed set of files that you know will not violate the assumptions.

But note that this is not proper parsing. Regular expressions cannot parse nested structures (like expressions inside balanced parenthesis), macros, and detecting strings with ; inside is possible but extremely cumbersome.

Parsing the all valid C++ is notoriously hard even with a full programming language.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.