Regex match in for loop

Brad Anderson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 15 13:33:19 PDT 2014


On Tuesday, 15 July 2014 at 20:18:58 UTC, seany wrote:
> Consider this:
>
> import std.stdio, std.regex, std.array, std.algorithms ;
>
> void main(string args[])
> {
>
> string[] greetings = ["hello", "hallo", "hoi", "salut"];
>
> regex r = regex("hello", "g");
>
> for(short i = 0; i < greetings.count(); i++)
> {
>
>   auto m = match(greetings[i], r);
> }
>
> }
>
> To the best of my knowledge, declaring a variable inside a for 
> loop is illegal, you can not delacre the same variable 
> repeatedly over the iterations.
>

There is nothing wrong with declaring a variable in a for loop. 
It's just limited to the scope inside the for loop so it's not 
useful if you need the variable after the for loop ends.

> Also just the declaration auto m; outside the for loop does not 
> make sense either - auto needs an Right Hand Side expression.
>
> So what is the correct way of doing it?

You can type out the return type. It can be a little tricky to 
determine sometimes though so you can also use typeof() like: 
typeof(match(greetings[i], r) m; to get the proper type.

You should use matchFirst and matchAll instead of match and the 
"g" flag. It's more clear and easier to use.

What are you trying to do in this bit of code? There may be a 
better overall structure.


More information about the Digitalmars-d-learn mailing list