Home >Backend Development >C++ >How Can I Reliably Detect C 'for' and 'while' Loops Ending with a Semicolon?
Detecting C "for" and "while" Loops with Semi-Colon Termination
Matching C for or while loops that end with a semi-colon using a regular expression can be challenging. A common approach involves creating a named group to match balanced substrings, ensuring that the entire loop body is contained within parentheses.
However, this method falters when the loop body includes a function call, breaking the balance. A simplified approach using a non-regex function can overcome this issue.
Custom Function for Loop Matching
The following custom function takes an input string and searches for a for or while loop followed by a semi-colon:
def find_loop_and_semicolon(string): pos = string.find('(') + 1 open_br = 0 while open_br >= 0: char = string[pos] if char == '(': open_br += 1 elif char == ')': open_br -= 1 pos += 1 return pos if open_br == 0 and string[pos] == ';' else -1
The function:
Usage
string = "for (int i = 0; i < 10; doSomethingTo(i));" result = find_loop_and_semicolon(string) if result != -1: print("Loop found and terminated with a semi-colon.") else: print("No matching loop found.")
Advantages
The above is the detailed content of How Can I Reliably Detect C 'for' and 'while' Loops Ending with a Semicolon?. For more information, please follow other related articles on the PHP Chinese website!