0

I'm using the RegexBuddy utility, with the regex

 ^\s*for\s.*:(?!:).*$

Which I would paraphrase as 'search lines with optional leading white-space, the text 'for', a single white space, then the rest of the line containing a colon, but not two colons together'.

Which mostly works, but the two colon exclusion doesn't (they are typically iterator references).

What's the correct regex for this search?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Tony Rietwyk
  • 65
  • 1
  • 7
  • Maybe `^\s*for\b[^:]*:[^:]*$`? – Wiktor Stribiżew Sep 01 '16 at 08:39
  • What if there is no space between the `for` and the opening parentheses (i.e. something like `for(x:y)`)? What if there is multiple spaces? – Some programmer dude Sep 01 '16 at 08:40
  • You've already got a working answer from @WiktorStribiżew. But just to explain why your doesn't work - the *first* `:` in your regex can also match the second in your input, making the second `:` of the regex **not** match the character after the second in the input. ` for abc::def` matches (not) `:d`. – SamWhan Sep 01 '16 at 08:57
  • In theory, [can C++ code be parsed with regular expressions](http://stackoverflow.com/questions/14589346/is-c-context-free-or-context-sensitive)? Can it be partially parsed (e.g. so only `for` loops should be found)? – Ivan Aksamentov - Drop Sep 01 '16 at 09:04

2 Answers2

1

The for statement does not have to be preceded by a space, nor is a space required between for and the opening brace. But OK, here's my attempt:

^\s*for\s*\([^)]*[^:]:[^:][^)]*\).*


Note: In general, it is all but impossible to accurately parse C++ code with a regex. You need a stateful parser to filter out nested comments, etc.

rustyx
  • 80,671
  • 25
  • 200
  • 267
0

I would use this regex (it works with grep, not sure about RegexBuddy):

^\s*for\s*(.\+[^:]:[^:].\+).*$

The essential part is in [^:]:[^:] which only matches a single colon (not immediately preceded or succeeded by another colon) within an arbitrary text inside a pair of parentheses.

EDIT RustyX's comment suggests that a regex that will match only range-fors is not possible, because it can always be tricked by the colon of a conditional (?:) operator.

Community
  • 1
  • 1
Leon
  • 31,443
  • 4
  • 72
  • 97