Thread overview
RegExp
Oct 15, 2008
DF
Oct 15, 2008
Sergey Gromov
Oct 15, 2008
DF
October 15, 2008
/**
 * RegExp test.
 */
import std.regexp;
import std.stdio;

void main() {
	string someString = "Hello world!";
	auto regExp = new RegExp(r"[wW]orld");
	auto result = regExp.search(someString);
	//int k = regExp.test(someString);
	if (result is null) {
		writefln("Not found!");
	} else {
		writefln("Result:" ~ result[0]);
	}
}

This code never writes the searched part, until we uncomment the line with test() method call, though there is a word matching the pattern. Why?
October 15, 2008
Wed, 15 Oct 2008 18:01:04 -0400,
DF wrote:
> /**
>  * RegExp test.
>  */
> import std.regexp;
> import std.stdio;
> 
> void main() {
> 	string someString = "Hello world!";
> 	auto regExp = new RegExp(r"[wW]orld");
> 	auto result = regExp.search(someString);
> 	//int k = regExp.test(someString);
> 	if (result is null) {
> 		writefln("Not found!");
> 	} else {
> 		writefln("Result:" ~ result[0]);
> 	}
> }
> 
> This code never writes the searched part, until we uncomment the line with test() method call, though there is a word matching the pattern. Why?

It shouldn't.  search() prepares the regexp for use in foreach loop.  The correct function for you is find:

import std.regexp;
import std.stdio;

void main() {
	string someString = "Hello world!";
	auto regExp = new RegExp(r"[wW]orld");
	auto result = regExp.find(someString);
	if (result == -1) {
		writefln("Not found!");
	} else {
		writefln("Result:" ~ regExp[0]);
	}
}
October 15, 2008
Sergey Gromov Wrote:

> Wed, 15 Oct 2008 18:01:04 -0400,
> DF wrote:
> > /**
> >  * RegExp test.
> >  */
> > import std.regexp;
> > import std.stdio;
> > 
> > void main() {
> > 	string someString = "Hello world!";
> > 	auto regExp = new RegExp(r"[wW]orld");
> > 	auto result = regExp.search(someString);
> > 	//int k = regExp.test(someString);
> > 	if (result is null) {
> > 		writefln("Not found!");
> > 	} else {
> > 		writefln("Result:" ~ result[0]);
> > 	}
> > }
> > 
> > This code never writes the searched part, until we uncomment the line with test() method call, though there is a word matching the pattern. Why?
> 
> It shouldn't.  search() prepares the regexp for use in foreach loop.  The correct function for you is find:
> 
> import std.regexp;
> import std.stdio;
> 
> void main() {
> 	string someString = "Hello world!";
> 	auto regExp = new RegExp(r"[wW]orld");
> 	auto result = regExp.find(someString);
> 	if (result == -1) {
> 		writefln("Not found!");
> 	} else {
> 		writefln("Result:" ~ regExp[0]);
> 	}
> }
Thanks.